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,nextSibling和previousSibling可以为我们完成这项工作。
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.
我们可以获取或设置元素的文本内容。 为了完成此任务,我们将使用两个属性: nodeValue和textContent 。
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?
您是否注意到nodeValue和textContent之间的区别?
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.
现在我们知道了如何处理元素,因此让我们学习如何处理这些元素的属性。 有一些方法,例如GetAttribute , setAttribute , hasAttribute , removeAttribute和一些属性,例如className和id 。
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