vanilla

by carlos da costa

通过卡洛斯·达·科斯塔

如何在Vanilla JavaScript中操作DOM (How to manipulate the DOM in Vanilla JavaScript)

So you have learned variables, selection structures, and loops. Now it is time to learn about DOM manipulation and to start doing some cool JavaScript projects.

因此,您已经了解了变量,选择结构和循环。 现在是时候学习DOM操作并开始做一些很棒JavaScript项目了。

In this tutorial, we will learn how to manipulate the DOM with vanilla JavaScript. With no further ado, let’s jump right into it.

在本教程中,我们将学习如何使用原始JavaScript操作DOM。 事不宜迟,让我们直接进入。

1.首先 (1. First things first)

Before we dive into coding, let’s learn what the Dom really is:

在开始编码之前,让我们学习一下Dom的真正含义:

The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects. That way, programming languages can connect to the page. Source

文档对象模型(DOM)是HTML和XML文档的编程接口。 它代表页面,以便程序可以更改文档的结构,样式和内容。 DOM将文档表示为节点和对象。 这样,编程语言可以连接到页面。 资源

Basically, when a browser loads a page it creates an object model of that page and prints it on the screen. The object model is represented in a tree data structure, each node is an object with properties and methods, and the topmost node is the document object.

基本上,浏览器在加载页面时会创建该页面的对象模型并将其打印在屏幕上。 对象模型以树形数据结构表示,每个节点是具有属性和方法的对象,而最顶层的节点是文档对象。

A programming language can be used to access and modify this object model, and this action is called DOM manipulation. And we will do that with JavaScript because JS is awesome.

可以使用一种编程语言来访问和修改此对象模型,此操作称为DOM操作。 我们将使用JavaScript来实现,因为JS非常棒。

2.实际教程 (2. The actual tutorial)

For the tutorial, we are going to need two files, one index.html, and the other manipulation.js.

对于本教程,我们将需要两个文件,一个为index.html,另一个为control.js。

<!-- Index.html file --><html>  <head>    <title>DOM Manipulation</title>  </head>  <body>     <div id="division"><h1 id="head"><em>DOM<em> manipulation</h1>      <p class="text" id="middle">Tutorial</p><p>Sibling</p>      <p class="text">Medium Tutorial</p>    </div>    <p class="text">Out of the div</p>    <!-- Then we call the javascript file -->    <script src="manipulation.js"></script>  </body></html>

So there we have our HTML file, and as you can see we have a div with the id of division. Inside of that we have an h1 element, and in the same line, you will understand why later, we have two p elements and the div closing tag. Finally we have a p element with a class of text.

这样我们就有了HTML文件,并且您可以看到我们有一个带除法ID的div。 在其中,我们有一个h1元素,并且在同一行中,您将了解为什么以后有两个p元素和div结束标记。 最后,我们有带有一类文本的ap元素。

2.1。 访问元素 (2.1. Accessing the elements)

We can either access a single element or multiple elements.

我们可以访问单个元素或多个元素。

2.1.1。 访问单个元素 (2.1.1. Accessing a single element)

For accessing a single element, we will look at two methods: getElementByID and querySelector.

为了访问单个元素,我们将看两种方法:getElementByID和querySelector。

// the method below selects the element with the id ofheadlet id = document.getElementById('head');
// the code below selects the first p element inside the first divlet q = document.querySelector('div p');
/* Extra code */// this changes the color to redid.style.color = 'red';// give a font size of 30pxq.style.fontSize = '30px';

Now we have accessed two elements, the h1 element with the id of head and the first p element inside the div.

现在,我们访问了两个元素,具有id为head的h1元素和div中的第一个p元素。

getElementById takes as argument an id, and querySelector takes as argument a CSS selector and returns the first element that matches the selector. As you can see I assigned the methods outcome into variables, and then I added some styling at the end.

getElementById将id作为参数, querySelector将CSS选择器作为参数,并返回与选择器匹配的第一个元素。 如您所见,我将方法的结果分配给变量,然后在最后添加一些样式。

2.1.2。 访问多个元素 (2.1.2. Accessing multiple elements)

When accessing multiple elements, a node list is returned. It is not an array but it works like one. So you can loop through it and use the length property to get the size of the node list. If you want to get a specific element you can either use the array notation or the item method. You will see them in the code.

当访问多个元素时,将返回一个节点列表。 它不是数组,但是像一个数组。 因此,您可以遍历它,并使用length属性来获取节点列表的大小。 如果要获取特定元素,则可以使用数组符号或item方法。 您将在代码中看到它们。

For accessing multiple elements we are going to use three methods: getElementsByClassName, getElementsByTagName, and querySelectorAll.

为了访问多个元素,我们将使用三种方法:getElementsByClassName,getElementsByTagName和querySelectorAll。

// gets every element with the class of textlet className = document.getElementsByClassName('text');
// prints the node listconsole.log(className);
/* prints the third element from the node list using array notation */console.log(className[2]);
/* prints the third element from the node list using the item function */console.log(className.item(2));
let tagName = document.getElementsByTagName('p');let selector = document.querySelectorAll('div p');

The code seems to be self-explanatory, but I will explain it anyway because I am a nice dude. :)

该代码似乎是不言自明的,但是我还是会解释它,因为我是一个好人。 :)

First, we use the getElementsByClassName that takes a class name as an argument. It returns a node list with every element that has text as a class. Then we print the node list on the console. We also print the third element from the list using the array notation and the item method.

首先,我们使用以类名作为参数的getElementsByClassName 。 它返回一个节点列表,其中每个元素都有以文本为类的元素。 然后我们在控制台上打印节点列表。 我们还使用数组符号item方法从列表中打印第三个元素。

Second, we select every p element using the getElementsByTagName method that takes a tag name as an argument and returns a node list of that element.

其次,我们使用getElementsByTagName方法选择每个p元素,该方法将标签名称作为参数并返回该元素的节点列表。

Finally, we use the querySelectorAll method, that takes as an argument a CSS selector. In this case, it takes div p so it will return a node list of p elements inside a div.

最后,我们使用querySelectorAll方法,该方法将CSS选择器作为参数。 在这种情况下,它需要div p,因此它将返回div中p个元素的节点列表。

As a practice exercise, print all the elements from tagName and selector node list and find out their size.

作为练习,打印来自tagName选择器节点列表的所有元素,并找出它们的大小。

2.2。 遍历DOM (2.2. Traversing the DOM)

So far we have found a way of accessing specific elements. What if we want to access an element next to an element that we have already accessed, or access the parent node of a previously accessed element? The properties firstChild, lastChild, parentNode, nextSibling, and previousSibling can get this job done for us.

到目前为止,我们已经找到了访问特定元素的方法。 如果我们要访问已经访问过的元素旁边的元素,或者访问以前访问过的元素的父节点,该怎么办? 属性firstChild,lastChild,parentNode,nextSiblingpreviousSibling可以为我们完成这项工作。

firstChild is used to get the first child element of a node. lastChild, as you guessed, it gets the last child element of a node. parentNode is used to access a parent node of an element. nextSibling gets for us the element next to the element already accessed, and previousSibling gets for us the element previous to the element already accessed.

firstChild用于获取节点的第一个子元素。 如您所猜, lastChild ,它获取节点的最后一个子元素。 parentNode是 用于访问元素的父节点。 nextSibling为我们获取已访问元素旁边的元素,而previousSibling为我们获取已访问元素之前的元素。

// gets first child of the element with the id of divisionlet fChild = document.getElementById('division').firstChild;console.log(fChild);
// gets the last element from element with the id of divisionlet lChild = document.querySelector('#division').lastChild;
// gets the parent node of the element with the id divisionlet parent = document.querySElector('#division').parentNode;console.log(parent);
// selects the element with the id of middlelet middle = document.getElementById('middle');// prints ond the console the next sibling of middleconsole.log(middle.nextSibling);

The code above first gets the firstChild element of the element with the division id and then prints it on the console. Then it gets the lastChild element from the same element with the division id. Then it gets the parentNode of the element with the id of division and prints it on the console. Finally, it selects the element with the id of middle and prints its nextSibling node.

上面的代码首先获取具有分区ID的元素的firstChild元素,然后将其打印在控制台上。 然后,它从具有除法ID的同一元素中获取lastChild元素。 然后,它获取具有除法ID的元素的parentNode并将其打印在控制台上。 最后,它选择id为middle的元素并打印其nextSibling节点。

Most browsers treat white spaces between elements as text nodes, which makes these properties work differently in different browsers.

大多数浏览器将元素之间的空白视为文本节点,这使得这些属性在不同的浏览器中的工作方式有所不同。

2.3。 获取和更新元素内容 (2.3. Get and Updating element content)

2.3.1. Setting and getting text Content

2.3.1。 设置和获取文字内容

We can get or set the text content of elements. To achieve this task we are going to use two properties: nodeValue and textContent.

我们可以获取或设置元素的文本内容。 为了完成此任务,我们将使用两个属性: nodeValuetextContent

nodeValue is used to set or get the text content of a text node. textContent is used to set or get the text of a containing element.

nodeValue用于设置或获取文本节点的文本内容。 textContent用于设置或获取包含元素的文本。

// get text with nodeValuelet nodeValue = document.getElementById('middle').firstChild.nodeValue;console.log(nodeValue);
// set text with nodeValuedocument.getElementById('middle').firstChild.nodeValue = "nodeValue text";
// get text with textContentlet textContent = document.querySelectorAll('.text')[1].textContent;console.log(textContent);
// set text with textContentdocument.querySelectorAll('.text')[1].textContent = 'new textContent set';

Did you notice the difference between nodeValue and textContent?

您是否注意到nodeValuetextContent之间的区别?

If you look carefully at the code above, you will see that for us to get or set the text with nodeValue, we first had to select the text node. First, we got the element with the middle id, then we got its firstChild which is the text node, then we got the nodeValue which returned the word Tutorial.

如果仔细看一下上面的代码,您将看到,要让我们使用nodeValue获取或设置文本,我们首先必须选择文本节点。 首先,我们获得具有中间 ID的元素,然后获得其firstChild (即文本节点),然后获得nodeValue并返回单词Tutorial。

Now with textContent, there is no need to select the text node, we just got the element and then we got its textContent, either to set and get the text.

现在有了textContent ,就无需选择文本节点,我们只需获取元素,然后获取其textContent即可设置和获取文本。

2.3.2. Adding and Removing HTML content

2.3.2。 添加和删​​除HTML内容

You can add and remove HTML content in the DOM. For that, we are going to look at three methods and one property.

您可以在DOM中添加和删除HTML内容。 为此,我们将研究三种方法和一种属性。

Let’s start with the innerHTML property because it is the easiest way of adding and removing HTML content. innerHTML can either be used to get or set HTML content. But be careful when using innerHTML to set HTML content, because it removes the HTML content that is inside the element and adds the new one.

让我们从innerHTML属性开始,因为它是添加和删除HTML内容的最简单方法。 innerHTML可以用于获取或设置HTML内容。 但是在使用innerHTML设置HTML内容时要小心,因为它会删除元素内HTML内容并添加新元素。

document.getElementById('division').innerHTML =`<ul>  <li>Angular</li>  <li>Vue</li>  <li>React</li></ul>`;

If you run the code, you will notice that everything else in the div with the id of division will disappear, and the list will be added.

如果运行代码,您会注意到div中ID为divid的所有其他内容都将消失,并将添加列表。

We can use the methods: createElement(), createTextNode(), and appendChild() to solve this problem.

我们可以使用以下方法: createElement() ,c reateTextNode()appendChild()解决此问题。

createElement is used to create a new HTML element. creatTextNode used to create a text node, and appendChild is used to append a new element into a parent element.

createElement用于创建新HTML元素。 creatTextNode用于创建文本节点,appendChild用于将新元素附加到父元素中。

//first we create a new p element using the creatElementlet newElement = document.createElement('p');/* then we create a new text node and append the text node to the element created*/let text = document.createTextNode('Text Added!');newElement.appendChild(text);
/* then we append the new element with the text node into the div with the id division.*/document.getElementById('division').appendChild(newElement);

There is also a method called removeChild used to remove HTML elements.

还有一个称为removeChild的方法,用于删除HTML元素。

// first we get the element we want to removelet toBeRemoved = document.getElementById('head');// then we get the parent node, using the parentNOde propertylet parent = toBeRemoved.parentNode;/* then we use the removeChild method, with the element to be removed as a parameter.*/parent.removeChild(toBeRemoved);

So first we get the element that we want to remove, and then we get its parent node. Then we called the method removeChild to remove the element.

因此,首先获得要删除的元素,然后获得其父节点。 然后我们调用方法removeChild删除元素。

2.4。 属性节点 (2.4. Attribute node)

Now we know how to handle elements, so let’s learn how to handle the attributes of these elements. There are some methods like GetAttribute, setAttribute, hasAttribute, removeAttribute, and some properties like className and id.

现在我们知道了如何处理元素,因此让我们学习如何处理这些元素的属性。 有一些方法,例如GetAttributesetAttributehasAttributeremoveAttribute和一些属性,例如classNameid

getAttribute as its name may suggest, it is used to get an attribute. Like the class name, the id name, the href of a link or any other HTML attribute.

顾名思义, getAttribute用来获取属性。 像类名,ID名称,链接的href或任何其他HTML属性一样。

setAttribute is used to set a new attribute to an element. It takes two arguments, first the attribute and second the name of the attribute.

setAttribute用于为元素设置新属性。 它带有两个参数,第一个是属性,第二个是属性名称。

hasAttribute used to check if an attribute exists, takes an attribute as an argument.

hasAttribute用于检查属性是否存在,将属性作为参数。

removeAttribute used to remove an attribute, it takes an attribute as an argument.

removeAttribute用于删除属性,它接受属性作为参数。

Id this property is used to set or get the id of an element.

id此属性用于设置或获取元素的id。

ClassName is used to set or get the class of an element.

ClassName用于设置或获取元素的类。

// selects the first divlet d = document.querySelector('div');// checks if it has an id attribute, returns true/falseconsole.log('checks id: '+d.hasAttribute('id'));// set a new class attributed.setAttribute('class','newClass');// returns the class nameconsole.log(d.className);

I know I am a good dude, but that code is just self-explanatory.

我知道我是一个好家伙,但是该代码是不言自明的。

结论 (Conclusion)

That is it! We have learned so many concepts, but there is more to learn about DOM manipulation. What we have covered here gives you a good foundation.

这就对了! 我们已经学习了很多概念,但是还有更多关于DOM操作的知识。 我们在这里介绍的内容为您奠定了良好的基础。

Go ahead and practice, and create something new to cement this new knowledge.

继续练习,并创建一些新东西来巩固这一新知识。

Good day, good coding.

美好的一天,良好的编码。

翻译自: https://www.freecodecamp.org/news/dom-manipulation-in-vanilla-js-2036a568dcd9/

vanilla

vanilla_如何在Vanilla JavaScript中操作DOM相关推荐

  1. 如何在xaml文件中操作用户在后台代码定义的类(1)

    本文主要示例如何在xaml文件中操作用户使用C#代码自定义的类.主要步骤如下: 1.在VS2008中创建一个新项目CustomTypesInXaml,在此项目下我们新建两个类,一个是Client类,一 ...

  2. javascript中获取dom元素高度和宽度

    javascript中获取dom元素高度和宽度的方法如下: 网页可见区域宽: document.body.clientWidth 网页可见区域高: document.body.clientHeight ...

  3. 在JavaScript中操作Cookie

    在Windows系统中,cookie通常是被储存在C:\Documents and settings\用户名\cookie目录下(如果系统在C盘).其实每个cookie实际上就是一个文本文件,里面是用 ...

  4. js读取html元素scr,了解一下JavaScript中的DOM编程

    如何在HTML中使用JavaScript 元素 元素用于在HTML页面中嵌入或引入JavaScript脚本代码.该元素默认被定义在 元素中 1.type:该属性定义script元素包含或src引入的脚 ...

  5. vanilla_如何使用Vanilla JavaScript构建钢琴键盘

    vanilla Making a playable piano keyboard can be a great way to learn a programming language (besides ...

  6. javascript中操作字符串小结

    最近几次参加前端实习生招聘的笔试,发现很多笔试题都会考到字符串的处理,比方说去哪儿网笔试题.淘宝的笔试题等.如果你经常参加笔试或者也是一个过来人,相信你也跟我一样,发现字符串的处理是前端招聘过程中最常 ...

  7. java dom 获得子元素_在JavaScript中删除DOM节点的所有子元素

    我将如何删除JavaScript中DOM节点的所有子元素? 说我有以下(丑陋的)HTML: hello world 我抓住了我想要的节点,如下所示: var myNode = document.get ...

  8. vue computed 中操作DOM和给对象添加属性遇到的问题

    这两天使用vue做东西遇到一些问题,今天总结记录一下: 在computed中没法操作dom元素,比如 computed: {w() {return this.$refs.box.offsetWidth ...

  9. SilverLight学习笔记--如何在xaml文件中操作用户在后台代码定义的类(2)--示例篇:创建一个登录控件(原创)(转载本文请注明出处)...

    本文将示例如何运用前篇所写知识来建立一个用户自定义的登录控件.此控件界面非常简单,主要涉及的知识点是:   如何创建用户控件(包括对此控件的自定义事件和属性的编写,此处我们将创建一个名为LoginBo ...

最新文章

  1. 《我是一只IT小小鸟》读后感
  2. 综合实例_管线综合支吊架施工实例赏析,工艺流程全面
  3. python经典排序_python实现十大经典排序算法
  4. PAT_B_1006_Java(15分)
  5. 虚拟终端网络工程实施纪要
  6. SVN Error: Unreadable path encountered; access denied;
  7. Python_Bool
  8. Python - 进程/线程相关整理
  9. JAVA课程设计坦克大战源码
  10. 宏碁笔记本u盘装系统如何进入bios设置u盘启动图文教程
  11. 面试中有关接口测试和接口自动化的那些事 ~
  12. 地理坐标(经纬度)转换成投影坐标(XY坐标)
  13. php实现播放直播_php和腾讯直播的实现代码
  14. 改善羽毛球比赛心理有“妙招”
  15. Ubuntu 16.04卸载LibreOffice等不常用软件
  16. My97 WdatePicker 属性
  17. Sqlmap参数详解
  18. 共享单车项目、mongodb集群
  19. Axure的安装和组件库导入
  20. presto sql语法总结

热门文章

  1. chdir、getcwd、mkdir、rmdir函数
  2. java小程序查看器,成功拿到offer
  3. 大厂面试必问!50w字+的Java技术类校招面试题汇总
  4. 期权价格的上限和下限
  5. 移动前端框架重构几个关键问题
  6. instrumentation模拟很多activity的操作
  7. 密码中不能包含全角字符的正则表达式
  8. WordPress Option API(数据库储存 API)
  9. 三位对我影响最深的老师
  10. IOS CALayer的属性和使用