Get DOM nodes natively

Table of contents

1. Obtain through the top-level method of document

1. Get html tags

 2. Get the head tag

 3. Get the body tag

 Two, getElementBy series acquisition

1. ID acquisition

 2. Obtaining the class name

 3. Get the name attribute

4. Get the tag name

Three, query series acquisition 

1. Get an element through the query selector

2. Get a set of elements through the querry selector

4. Obtain through the properties of the node

1. Get the parent node

 2. Get child nodes

3. Get the first child node

4. lastChild gets the last child node

 5. Obtain sibling nodes


1. Obtain through the top-level method of document

1. Get html tags

There is a special method for getting html tags: document.documentElement

console.log(document.documentElement) icon

 2. Get the head tag

There is also a dedicated method for getting the head tag:document.head

console.log(document.body) icon

 3. Get the body tag

There is also a dedicated method for getting the body tag: document.body

console.log(document.body) icon

 Two, getElementBy series acquisition

1. ID acquisition

Syntax: document.getElementById('ID on the label')

print: document.getElementById('father'):

console.log(document.getElementById("father")) icon

Note: if two tags have the same ID, it will get the first tag

Add a div with id named father

 Print again console.log(document.getElementById("father"))

 2. Obtaining the class name

Syntax:  getElementsByClassName('Class name on the label')

print document.getElementsByClassName('box'):

console.log(document.getElementsByClassName(“box”))图示

 What is obtained is an array, because the class names in multiple tag names are the same, so what is obtained is an array

Return an array, document.getElementsByClassName('box')[0] to get the first label element in the label group whose class is box.

console.log(document.getElementsByClassName("box")[0]) icon

 3. Get the name attribute

Syntax: getElementsByName('name attribute value on the label')

By printing console.log( document.getElementsByName('fatherBox') ) on the console, you can see that a NodeList is returned on the console (the concept of NodeList is similar to the concept of HTMLCollection mentioned in the previous class name acquisition, but there are also Different, because this Xiaobai can’t explain it clearly, so please refer to the official bigwigs for details on Baidu) array,

4. Get the tag name

Syntax: documentsByTagName('tag name')

Print and you can see that an HTMLCollectiondocument.getElementsByTagName('div') array is returned , which contains all the divs in our HTML

console.log(document.getElementsByTagName("div"))Illustration

Three, query series acquisition 

When we only have the parent element with id, class, and name values ​​set, and then there is too much HTML content, it is not convenient to use the above four selectors at this time, so the query selector is added in HTML5 to help us more convenient The element is obtained.

1. Get an element through the query selector

Syntax: querySelector('select elements according to selector rules')

Note that it should be obtained according to the matching rules of the css selector. When the selector selects multiple contents , only the first matched element will be selected and returned , but the first one here is not the same as the first one selected by the previous ById selector. For example, if you accidentally give The two elements have the same Id, both are father, and there is no div in the first father, and there are multiple divs in the second father. At this time, the querySelector will first match the first father and then match inside, and find that there is no div If the matched div can be returned, it will enter the second father for matching, and return the first matched div; however, if there is a div that can be returned in the first father, then it will It will not match the second father. It may not be intuitive enough, let’s go directly to the picture:

(1) Two fathers, there is no div in the first father

Two fathers, there is no div in the first father

 print in consoledocument.querySelector('#father>div')

returns the first div of the second father

 (2) Two fathers, the first father has a div in it

Two fathers, the first father has a div in it

 print in consoledocument.querySelector('#father>div')

Returns the div matched in the first father

2. Obtain a set of elements through the query selector

Syntax: querySelectorAll('get elements according to css selector rules')

You can see that a NodeListdocument.querySelectorAll('#father>div') array is returned by printing on the console , which contains all the div elements that we matched through the matching rules.

console.log(document.querySelectorAll("#father>div")) icon

 Maybe some judges are curious. What will happen if you write more elements with repeated ids at this time? Don’t worry, I’ll print it out for you. It’s still the two fathers above. The first father has One div, the second father has a structure of three divs, and then print document.querySelectorAll('#father>div'):

 Print it again document.querySelectorAll("#father>div")

 We can see that he has acquired all the child divs in the parent element of the two repeated ids into the array.

4. Obtain through the properties of the node

Each DOM element can actually be regarded as an object. In this DOM element object, there are attributes used to obtain various nodes. We can obtain a node through the method introduced in the first section, and then operate on this node. The attribute gets the desired element node.

1. Get the parent node

Syntax: child node.parentNode gets the parent node

The parent node of the element is obtained through the parentNode attribute. For example, the document.getElementsByClassName('box2')[0].parentNodeparent node of the first element in the element array with the class name box2 can be obtained by printing on the console. The printed result is:

parentNode parent node attribute

 2. Get child nodes

Method 1 (not recommended): childNodes gets all child nodes

Syntax: parent node.childNodes

Obtain the parent node of the element through the childNodes attribute. For example, document.getElementById('father').childNodesyou can get all the child nodes under the element whose ID is father by printing on the console. By observing the console, we can see that a NodeList array is returned:

childNodes get all child nodes Figure 1

 We can see that there are some strange things in the array – text, this is actually a space we typed in the editor to make the code structure clearer. The head and tail of each child element will be parsed into text and added to the array if there is a space. It is difficult for us to operate such an array, so this method is not recommended .

Method 2 (recommended): chilNodes gets all child nodes

Syntax: parent node.children

Get all child nodes through children. This property returns an array like childNodes, but returns an HTMLCollection array. The results printed on the console document.getElementById('father').childrenare as follows:

children get all child nodes 1

 It can be seen that the array we obtained is not the same as the array of child nodes obtained by using childNodes, and there are no strange things in it – in this textcase, we can perform better demand operations, so if you want to use It is recommended to use children instead of childNodes when obtaining all child nodes through the properties of the node .

3. Get the first child node

Syntax: parent node.firstChild

When we want to get the first child node of an element, we can use the firstChild property. Also print it on the console to see the return result :console.log(document.getElementById('father').firstChild)

firstChild gets the first child node Figure 1

 We found that a familiar thing was printed out. It appeared in the array returned by childNodes earlier text. Then this should also be a problem of spaces. Delete the spaces in front of the first child node and take a look.

Remove the whitespace graph in front of the first child node

 firstChild gets the first child node Figure 2

 You can see that he returned exactly what we wanted.
Because he doesn't filter newline spaces and the like, it can be considered in disguise childNodes[0].

4. lastChild gets the last child node

When getting the last child node of an element, we can use the lastChild property. Also print it on the console to see the return result :console.log(document.getElementById('father').lastChild)

lastChild gets the last child node Figure 1

 It can be found that the problem of newlines and spaces is still the problem. The solution is slightly different from firstChild. FirstChild removes the gap in front of the first child node, while lastChild removes the gap behind the last child node:

Remove the gap graph behind the child node

 At this time, if you print again, you will get the last child node element we need:

lastChild gets the last child node Figure 2

 5. Obtain sibling nodes

(1), Get the previous sibling element

Syntax: sibling node.previousSibling

Use previousSiblingGet the previous sibling element document.getElementsByClassName('box2')[0].previousSiblingto get the previous sibling element of box2 through console printing:

Note: spaces and newlines will appear #text

 (1), get the next sibling element

Syntax:  sibling node.nextSibling

Use nextSiblingGet the next sibling element to document.getElementsByClassName('box2')[0].nextSiblingget the sibling element behind box2 through console printing:

Get the next sibling element map

summary: 

Several methods of text will be printed (childNodes to get all child nodes, firstChild to get the first child node, lastChild to get the last child node, previousSibling to get the previous sibling element, nextSibling to get the next sibling element), personally not recommended, edit now The editors are all formatted and beautified codes. If you accidentally change the line, it is really text everywhere.

Guess you like

Origin blog.csdn.net/qq_52421092/article/details/129803736