N ways to obtain elements in JS and their dynamic and static discussions

jacklove
Release: 2018-05-21 14:09:27
Original
1365 people have browsed it

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

 

hello world

hello dolby

hello dot

hello bean

//(1)处打印值

hello world

hello dolby

hello dot

hello bean

//(2)处打印值
Copy after login

Example:

 getElementById example 
 

Some text here

Copy after login

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!
Copy after login

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);
Copy after login

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代码

hello world

hello dolby

hello dot

hello bean

//js代码一
Copy after login

/ /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代码二  //(5)处打印值
//(6)处打印值[] //空的HTMLCollection集合,长度为0
Copy after login

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 } }
Copy after login

Example: Delete

 

hello world

hello dolby

hello dot

hello bean

Copy after login

示例:删除

 
red green blue
Copy after login

getElementByName返回的是一个NodeList动态集合

//(9)处打印值

"red""green""blue"
//(10)处打印值[] //空的NodeList集合,长度为0

5、querySelector():

接收一个参数:一个包含一个或多个CSS 选择器的字符串(多个选择器以逗号分隔),返回匹配指定CSS选择器的第一个元素节点(无法选中CSS伪元素),没有发现匹配的节点则返回null。
语法:

element = document.querySelector(selectors);

示例:一个强大的选择方式

//这个标签将被返回
Copy after login

示例:如果要匹配的ID或选择器不符合 CSS 语法(比如不恰当地使用了冒号或者空格),你必须用反斜杠将这些字符转义。由于 JavaScript 中,反斜杠是转义字符,所以当你输入一个文本串时,你必须将它转义两次(一次是为 JavaScript 字符串转义,另一次是为 querySelector 转义):

Copy after login

示例:删除

hello world

hello dolby

hello dot

hello bean

Copy after login
//(11)处打印值 

hello dolby

hello dot

hello bean

//(12)处打印值

hello world

//如你所见,querySelector也是静态的快照
Copy after login

6、querySelectorAll():

接收一个参数:一个包含一个或多个CSS 选择器的字符串(多个选择器以逗号分隔),返回静态NodeList对象集合,该集合中包含匹配指定CSS选择器的所有节点,元素节点的变化无法实时反映在结果中;如果参数中包含CSS伪元素则返回一个空的对象集合。
语法:

elementList = document.querySelectorAll(selectors);

示例:

var matches = document.querySelectorAll("div.note, div.alert");

示例:删除

hello world

hello dolby

hello dot

hello bean

Copy after login

//(13)处打印值

//(13)处打印值
[p.myP,p.myP,p.myP,p.myP] //返回的是静态NodeList集合,元素节点的变化无法实时反映在结果中

7、elementFromPoint():

接收两个参数:分别是相对于当前窗口左上角的横纵坐标,单位为CSS像素,不需要加单位;返回位于页面指定位置的元素,如果该元素不可返回(如滚动条)则返回它的父元素,如果坐标值无意义(如负值)则返回null。
语法

var element = document.elementFromPoint(x, y);

示例:

elementFromPoint example 
 

Some text here

Copy after login

这一个获取元素的方法用得不多所以不多做介绍。

是不是觉得看了上面这些头好大啊,什么是动态什么是静态,有没有好记一点的方法呢?
有哒!

你可以简单地理解为,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]"
Copy after login

不同点:

NodeList 对象会包含文档中的所有节点,如 Element、Text 和 Comment 等;HTMLCollection 对象只会包含文档中的 Element 节点

本篇对hs获取元素进行了详细的讲解,更多相关内容请关注php中文网。

相关推荐:

JavaScript全总结之DOM的Element

实现jquery懒加载、回到顶部

关于this的相关问题

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!