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.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)
与getElementByClassName相同,返回动态集合,所以循环删除结果也相同
//(7)处打印值
//(8)处打印值[] //空的HTMLCollection集合,长度为0
4、getElementsByName():
接收一个参数:带有给定name属性值的元素,返回一个动态NodeList类数组对象,对象中包含以当前元素为根节点,所有指定name属性值的子元素。最常用的场景是取得单选按钮。
示例:
<!DOCTYPE html><html lang="en"><head> ...</head><body> <form name="up"><input type="text"></form><div name="down"><input type="text"></div> <script>var up_forms = document.getElementsByName("up");console.log(up_forms[0].tagName); // returns "FORM"</script></body></html>
示例:删除
<body> <div id="myDiv"> <input type="radio" name="fav-color">red <input type="radio" name="fav-color">green <input type="radio" name="fav-color">blue </div> <script> var div = document.getElementById("myDiv"); console.log(div); //(9) var ipt_favCol = document.getElementsByName("fav-color"); for (var i = ipt_favCol.length; i--;) { div.removeChild(ipt_favCol[i]); } console.log(ipt_favCol); //(10) </script></body>
getElementByName返回的是一个NodeList动态集合
//(9)处打印值
//(10)处打印值[] //空的NodeList集合,长度为0
5、querySelector():
接收一个参数:一个包含一个或多个CSS 选择器的字符串(多个选择器以逗号分隔),返回匹配指定CSS选择器的第一个元素节点(无法选中CSS伪元素),没有发现匹配的节点则返回null。
语法:
element = document.querySelector(selectors);
示例:一个强大的选择方式
<div class="user-panel main"> <input name="login"/> //这个标签将被返回</div><script> var el = document.querySelector("div.user-panel.main input[name=login]"); </script>
示例:如果要匹配的ID或选择器不符合 CSS 语法(比如不恰当地使用了冒号或者空格),你必须用反斜杠将这些字符转义。由于 JavaScript 中,反斜杠是转义字符,所以当你输入一个文本串时,你必须将它转义两次(一次是为 JavaScript 字符串转义,另一次是为 querySelector 转义):
<div id="foo\bar"></div><div id="foo:bar"></div><script> console.log('#foo\bar') // "#fooar" document.querySelector('#foo\bar') // 不匹配任何元素 console.log('#foo\\bar') // "#foo\bar" console.log('#foo\\\\bar') // "#foo\\bar" document.querySelector('#foo\\\\bar') // 匹配第一个div document.querySelector('#foo:bar') // 不匹配任何元素 document.querySelector('#foo\\:bar') // 匹配第二个div</script>
示例:删除
<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); //(11) var p = document.querySelector("p"); div.removeChild(p); console.log(p); //(12) </script>
//(11)处打印值 <div id="myDiv"> <p class="myP">hello dolby</p> <p class="myP">hello dot</p> <p class="myP">hello bean</p> </div>//(12)处打印值 <p class="myP">hello world</p> //如你所见,querySelector也是静态的快照
6、querySelectorAll():
接收一个参数:一个包含一个或多个CSS 选择器的字符串(多个选择器以逗号分隔),返回静态NodeList对象集合,该集合中包含匹配指定CSS选择器的所有节点,元素节点的变化无法实时反映在结果中;如果参数中包含CSS伪元素则返回一个空的对象集合。
语法:
elementList = document.querySelectorAll(selectors);
示例:
var matches = document.querySelectorAll("div.note, div.alert");
示例:删除
<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); //(13) var p = document.querySelectorAll("p"); for (var i = 0; i < p.length; i++) { div.removeChild(p[i]); } console.log(p); //(14) </script>
//(13)处打印值
//(13)处打印值
[p.myP,p.myP,p.myP,p.myP] //返回的是静态NodeList集合,元素节点的变化无法实时反映在结果中
7、elementFromPoint():
接收两个参数:分别是相对于当前窗口左上角的横纵坐标,单位为CSS像素,不需要加单位;返回位于页面指定位置的元素,如果该元素不可返回(如滚动条)则返回它的父元素,如果坐标值无意义(如负值)则返回null。
语法
var element = document.elementFromPoint(x, y);
示例:
<!DOCTYPE html><html lang="en"><head><title>elementFromPoint example</title><script>function changeColor(newColor) { elem = document.elementFromPoint(2, 2); 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>
这一个获取元素的方法用得不多所以不多做介绍。
是不是觉得看了上面这些头好大啊,什么是动态什么是静态,有没有好记一点的方法呢?
有哒!
你可以简单地理解为,getElementBy系列返回的都是动态的HTMLCollection集合,动态集合中的DOM结构变化能实时地反映到所保存的对象中,而querySelector系列返回的都是静态的NodeList对象,是一个快照,对DOM的任何操作都不会对其产生影响。
那么Nodelist和HTMLCollection有什么异同呢?
相同点:
二者都是类数组对象
二者都具有length属性
二者都具有item()方法
二者都是动态的元素集合,每次访问都需要重新对文档进行查询。
你一定会好奇,诶?前面不是说querySelector系列返回的都是静态的NodeList对象咩?怎么又变成动态的呢?原因在此:
规范中对 querySelectorAll 有明确要求,规定其必须返回一个静态的 NodeList 对象。
在Chrome中情况如下:
document.querySelectorAll('a').toString(); // return "[object NodeList]"document.getElementsByTagName('a').toString(); // return "[object HTMLCollection]"
不同点:
NodeList 对象会包含文档中的所有节点,如 Element、Text 和 Comment 等;HTMLCollection 对象只会包含文档中的 Element 节点
本篇对hs获取元素进行了详细的讲解,更多相关内容请关注php中文网。
相关推荐:
The above is the detailed content of N ways to obtain elements in JS and their dynamic and static discussions. For more information, please follow other related articles on the PHP Chinese website!