


N ways to obtain elements in JS and their dynamic and static discussions
In the process of learning JavaScript, you will encounter the problem of js obtaining elements. This article will explain the method of obtaining elements.
In actual front-end development work, we often encounter the need to obtain certain elements in order to update the style, content, etc. of the element. The Document Object Model (DOM) is a programming interface for HTML and XML documents. It provides a structured representation of the document and defines a way to access the structure from the program, thereby changing the structure and style of the document. and content. The DOM parses a document into a structured collection of nodes and objects (objects containing properties and methods), which connects web pages to scripts or programming languages. Therefore, JavaScript can obtain element nodes through the DOM API. The methods are as follows: querySelector() and querySelectorAll() are the ES5 element selection methods
1, getElementById():
Receives a parameter: the ID of the element to be obtained (case-sensitive, must match strictly), returns an Element object (can also be regarded as a dynamic NodeList collection, except that the collection only contains one matching element, but it will also reflect the DOM in real time Node changes), if the element with a specific ID does not exist in the current document, nul is returned.
Syntax:
element = document.getElementById(id);
Example: Delete
<body> <div id="myDiv"> <p class="myP">hello world</p> <p class="myP">hello dolby</p> <p class="myP">hello dot</p> <p class="myP">hello bean</p> </div> <script> var div = document.getElementById("myDiv"); console.log(div); //(1) var body=document.querySelector('body'); body.removeChild(div); console.log(body); //(2) </script></body> //(1)处打印值 <div id="myDiv"> <p class="myP">hello world</p> <p class="myP">hello dolby</p> <p class="myP">hello dot</p> <p class="myP">hello bean</p> </div>//(2)处打印值<body> <script> var div = document.getElementById("myDiv"); console.log(div); //(1) var body=document.querySelector('body'); body.removeChild(div); console.log(body); //(2) </script></body>
Example:
<!DOCTYPE html><html><head> <title>getElementById example</title> <script> function changeColor(newColor) { var elem = document.getElementById("para1"); elem.style.color = newColor; } </script></head><body> <p id="para1">Some text here</p> <button onclick="changeColor('blue');">blue</button> <button onclick="changeColor('red');">red</button></body></html>
getElementById( ) method will not search for elements that are not in the document. After creating an element and assigning an ID, you must use insertBefore() or other similar methods to insert the element into the document before you can use getElementById() to obtain:
var element = document.createElement("div"); element.id = 'testqq';var el = document.getElementById('testqq'); // el will be null!
2, getElementsByClassName():
Receives a parameter, which is a string containing one or more class names (class names are separated by spaces), and returns an HTMLCollection dynamic collection (it can also be said to return a NodeList class array object), which contains the current element. As the root node, all child elements with specified class names.
Syntax:
var elements = document.getElementsByClassName(names); var elements = rootElement.getElementsByClassName(names);
getElementsByClassName can be called on any element, not just document. The element calling this method will be used as the root element for this search.
Example:
Get all elements with class 'test':
document.getElementsByClassName('test');
Get all elements including class Elements of 'red' and 'test':
document.getElementsByClassName('red test');
In the child nodes of the element with the id of 'main', get all Elements with class 'test':
document.getElementById('main').getElementsByClassName('test');
Example: Delete
//html代码<div class="myDiv"> <p class="myP">hello world</p> <p class="myP">hello dolby</p> <p class="myP">hello dot</p> <p class="myP">hello bean</p> </div> //js代码一 <script> var div = document.getElementsByClassName("myDiv"); console.log(div); //(3) var p = document.getElementsByClassName("myP"); for (var i = 0; i < p.length; i++) { div[0].removeChild(p[i]); } console.log(p); //(4) </script>
/ /Print value at (3)
[div.myDiv] //A dynamic HTMLCollection collection, length is 1, innerHTML is
hello dolby
,hello bean
, why there are no other two p elements will be explained later.//Print value at (4)
[p.myP,p.myP] //A dynamic HTMLCollection collection with a length of 2 and innerHTML respectively "hello dolby" and "hello bean" .
The above method of deleting nodes has been used to verify that the getElementsByClassName method returns an HTMLCollection dynamic collection.
⬆️In the above code, first div obtains a dynamic collection composed of elements with the class name "myDiv" in the page, p obtains a dynamic collection composed of elements with the class name "myP" in the page, and then uses A for loop to delete each item in the "myP" collection in the first item in the "myDiv" collection (that is, the only div element in the above example). As a result, only the first and third items are deleted. This is why?
The reason is that changes in the DOM structure in the dynamic collection can be automatically reflected in the saved objects. Initially p.legth=4, when i=0, the first p element in the page is deleted, and thereafter p.length= 3; When i=1, the item with index 1 in the remaining three p is deleted, and then p.length=2; when i=2, the condition of i
So how can we traverse each item in the HTMLCollection collection of array-like objects and delete all items?
It’s still a for loop⬇️, just delete the last item in the object collection each time ~
//js代码二 <script> var div = document.getElementsByClassName("myDiv")[0]; console.log(div); //(5) var p = document.getElementsByClassName("myP"); for (var i=p.length;i--;){ div.removeChild(p[i]); } console.log(p); //(6) </script> //(5)处打印值<div class="myDiv"></div>//(6)处打印值[] //空的HTMLCollection集合,长度为0
3. getElementsByTagName():
Receives one parameter: to be obtained The tag name of the element (not case sensitive), returns an HTMLCollection dynamic collection (it can also be said to return a NodeList class array object), the collection contains the current element as the root node (excluding the current element itself), all the specified tag names Child elements, the order of child elements is the order in which they appear in the subtree of the current element. If no element is found, the set will be empty.
Syntax:
elements = element.getElementsByTagName(tagName)
Example:
// check the alignment on a number of cells in a table. var table = document.getElementById("forecast-table"); var cells = table.getElementsByTagName("td"); for (var i = 0; i < cells.length; i++) { var status = cells[i].getAttribute("data-status"); if ( status == "open" ) { // grab the data } }
Example: Delete
<body> <div id="myDiv"> <p class="myP">hello world</p> <p class="myP">hello dolby</p> <p class="myP">hello dot</p> <p class="myP">hello bean</p> </div> <script> var div = document.getElementById("myDiv"); console.log(div); //(7) var p = document.getElementsByTagName("p");//
以下for循环改为for (var i=0,len=p.length;i
div.removeChild(p[i]);
} console.log(p); //(8)