Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the difference between querySelector and getElementById methods in JavaScript

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "what is the difference between querySelector and getElementById method in JavaScript". In daily operation, I believe many people have doubts about the difference between querySelector and getElementById method in JavaScript. Xiaobian consulted all kinds of information and sorted out simple and easy operation methods. I hope to answer the doubts of "what is the difference between querySelector and getElementById method in JavaScript"! Next, please follow the small series to learn together!

1. overview

When looking at the code, I found that basically all elements are obtained with querySelector() and querySelectorAll(), wondering why not getElementById().

Perhaps because he had not used those two before, he did not know why.

1.1 querySelector() and querySelectorAll() usage

querySelector() method

Definition: The querySelector() method returns an element in the document that matches the specified CSS selector;

Note: The querySelector() method returns only the first element that matches the specified selector. If you need to return all elements, use the querySelectorAll() method instead;

syntax: document.querySelector(CSS selectors);

Parameter value: String Required. CSS selectors that specify one or more matching elements. Select elements using their id, class, type, attribute, attribute value, etc.

For multiple selectors, separated by commas, return a matching element.

Return Value: Matches the first element of the specified CSS selector. If not found, return null. SYNTAX_ERR exception thrown if illegal selector specified.

querySelectorAll() method

Definition: The querySelectorAll() method returns all elements in the document that match the specified CSS selector, returning a NodeList object;

NodeList objects represent collections of nodes. It can be accessed by index, and the index value starts from 0;

Tip: You can use the length attribute of the NodeList object to get the element attributes of the matching selector, and then traverse all the elements to get the desired information;

syntax: elementList = document.querySelectorAll(selectors);

elementList is a static NodeList object;

selectors is a string of one or more CSS selectors concatenated by commas;

Parameter value: String Required. Specifies one or more elements that match CSS selectors. You can get elements by id, class, type, attribute, attribute value, etc. as selectors.

Multiple selectors are separated by commas (,).

Return value: A NodeList object representing all elements in the document that match the specified CSS selector.

NodeList is a static NodeList object. If the specified selector is illegal, a SYNTAX_ERR exception is thrown.

1.2 getElement(s)Byxxxx Usage

getElementById() method

Definition: The getElementById() method returns a reference to the first object with the specified ID.

Returns null if there is no element with the specified ID;

If there are more than one element with the specified ID, return the first one;

If you need to find elements that don't have an ID, consider using querySelector() via CSS selector;

Syntax: document.getElementById(elementID);

Parameter value: String Required. Element ID attribute value.

Return value: Element object Element with specified ID

getElementsByTagName() method

Definition: The getElementsByTagName() method returns a collection of objects with the specified tagname;

Tip: Parameter value "*" returns all elements of the document;

Syntax: document.getElementsByTagName(tagname)

Parameters: String Must obtain the tag name of the element;

Return value: NodeList object A collection of elements with a specified tag name

getElementsByClassName() method

Definition: The getElementsByClassName() method returns a collection of all elements of the specified class name in the document as a NodeList object.

The NodeList object represents an ordered list of nodes. The NodeList object accesses the nodes in the table by the node index number in the node list (index number starts with 0).

Tip: You can use the length attribute of the NodeList object to determine the number of elements of a given class name and loop through each element to get the one you want.

Syntax: document.getElementsByClassName(classname)

Parameter: String The element class name that must be obtained. Multiple class names are separated by spaces, such as "test demo";

Return value: NodeList object, representing the collection of elements of the specified class name. The order of elements in the collection is sorted by the order in which they appear in the code.

2. Difference 2.1 getElement(s)Byxxxx gets a dynamic collection, querySelector gets a static collection

Dynamic means that the selected elements will change with the document, and the static ones will not be taken out and have nothing to do with the change of the document.

Example 1:

Test 1 test 2 test 3 //Get ul, in order to dynamically add li var ul = document.getElementById ('box ') later; //Get li var list = ul.getElementsByTagName ('li'); for(var i =0; i) from existing ul

< list.length; i++){ ul.appendChild(document.createElement('li')); //动态追加li } 上述代码会陷入死循环,i < list.length 这个循环条件。 因为在第一次获取到里面的 3 个 li 后,每当往 ul 里添加了新元素后,list便会更新其值,重新获取ul里的所有li。 也就是 getElement(s)Byxxxx 获取的是动态集合,它总会随着 dom 结构的变化而变化。 也就是每一次调用 list 都会重新对文档进行查询,导致无限循环的问题。 示例1 修改: 将 for 循环条件修改为 i < 4,结果 在 ul 里新添加了4个元素,所有现在插入的 li 标签数量是7。 测试1 测试2 测试3 var ul = document.getElementById('box'); var list = ul.getElementsByTagName('li'); for(var i = 0; i < 4; i++){ ul.appendChild(document.createElement('li')); } console.log('list.length:',list.length); 示例2: 下述代码静态集合体现在 .querySelectorAll('li') 获取到 ul 里所有 li 后,不管后续再动态添加了多少 li,都是不会对其参数影响。 测试1 测试2 测试3 var ul = document.querySelector('ul'); var list = ul.querySelectorAll('li'); for(var i = 0; i < list.length; i++){ ul.appendChild(document.createElement('li')); } console.log('list.length:',list.length); //输出的结果仍然是 3,不是此时 li 的数量 6

Why is it designed this way?

The querySelectorAll method is specified in the W3C specification:

The NodeList object returned by the querySelectorAll() method must be static ([DOM], section 8).

Let's see what happens in Chrome:

document.querySelectorAll('a').toString(); // return "[object NodeList]"

document.getElementsByTagName('a').toString(); // return "[object HTMLCollection]"

HTMLCollection is defined by the W3C as follows:

An HTMLCollection is a list of nodes. An individual node may be accessed by either ordinal index or the node's name or id attributes.Note: Collections in the HTML DOM are assumed to be live meaning that they are automatically updated when the underlying document is changed.

In fact, HTMLCollections and NodeLists are very similar, both are dynamic collections of elements, and each access requires a re-query of the document.

Difference: HTMLCollection belongs to Document Object Model HTML specification, while NodeList belongs to Document Object Model Core specification.

This is a bit hard to understand, but look at the following example:

var ul = document.getElementsByTagName('ul')[0], lis1 = ul.childNodes, lis2 = ul.children;console.log(lis1.toString(), lis1.length); // "[object NodeList]" 11console.log(lis2.toString(), lis2.length); // "[object HTMLCollection]" 4

The NodeList object contains all the nodes in the document, such as Element, Text, and Comment.

HTMLCollection objects will contain only Element nodes in the document;

In addition, HTMLCollection objects provide one more namedItem method than NodeList objects;

So in the browser, the return value of querySelectorAll is a static NodeList object, while the return value of the getElementsBy series is actually an HTMLCollection object.

2.2 Different parameters received

The querySelectorAll method receives a CSS selector as an argument;

getElementsBy series can only accept single className, tagName and name parameters;

var c1 = document.querySelectorAll('.b1 .c');var c2 = document.getElementsByClassName('c');var c3 = document.getElementsByClassName('b2')[0].getElementsByClassName('c');

Note: querySelectorAll receives parameters that must strictly conform to CSS selector specifications

This will throw an exception (element names, classes, and IDs in CSS selectors cannot start with a number).

try { var e1 = document.getElementsByClassName ('1a 2b 3c'); var e2 = document.querySelectorAll ('.1a2b3c');} catch (e) { console.error(e.message);}console.log(e1 && e1[0].className);console.log(e2 && e2[0].className);2.3 Browser compatibility varies

querySelectorAll is supported by IE 8+, FF 3.5+, Safari 3.1+, Chrome and Opera 10+;

getElementsBy series, taking getElementsByClassName in the latest addition specification as an example, IE 9+, FF 3 +, Safari 3.1+, Chrome and Opera 9+ are already supported;

2.4 querySelector belongs to the Selectors API specification in W3C, while getElementsBy series belongs to the DOM specification of W3C. The study of "what is the difference between querySelector and getElementById method in JavaScript" is over, hoping to solve everyone's doubts. Theory and practice can better match to help everyone learn, go and try it! If you want to continue learning more relevant knowledge, please continue to pay attention to the website, Xiaobian will continue to strive to bring more practical articles for everyone!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report