In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "what are the differences between querySelector and getElementById methods in JS". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Catalogue
1. Overview
1.1 usage of querySelector () and querySelectorAll ()
1.2 usage of getElement (s) Byxxxx
two。 Difference
2.1 getElement (s) Byxxxx gets dynamic collections, querySelector gets static collections
2.2 different parameters are received
2.3 browsers are compatible with different
1. Overview
When I look at the code, I find that I basically use querySelector () and querySelectorAll () to get elements, and I wonder why I don't use getElementById ().
Maybe it's because I haven't used those two, so I don't know why.
1.1 usage of querySelector () and querySelectorAll ()
QuerySelector () method
Definition: the querySelector () method returns an element in the document that matches the specified CSS selector
Note: the uerySelector () method returns only the first element that matches the specified selector. If you need to return all the elements, use the querySelectorAll () method instead
Syntax: document.querySelector (CSS selectors)
Parameter value: String must be. Specifies a CSS selector for one or more matching elements. Use their id, classes, types, attributes, attribute values, etc., to select elements.
For multiple selectors, separate them with commas and return a matching element.
Return value: matches the first element of the specified CSS selector. If it is not found, return null. If an illegal selector is specified, a SYNTAX_ERR exception is thrown.
QuerySelectorAll () method
Definition: the querySelectorAll () method returns all elements in the document that match the specified CSS selector, and returns the NodeList object
The NodeList object represents a collection of nodes. Can be accessed through the index, with the index value starting at 0
Tip: you can use the length attribute of the NodeList object to get the element attributes of the matching selector, and then iterate through all the elements to get the information you want
Syntax: elementList = document.querySelectorAll (selectors)
ElementList is a static object of type NodeList
Selectors is a comma concatenated string containing one or more CSS selectors
Parameter value: String must be. Specifies one or more elements that match the CSS selector. Elements can be obtained by using id, class, type, attribute, attribute value, and so on as selectors.
Multiple selectors are separated by commas (,).
Return value: a NodeList object that represents all elements in the document that match the specified CSS selector.
NodeList is a static object of type NodeList. If the specified selector is illegal, a SYNTAX_ERR exception is thrown.
1.2 usage of getElement (s) Byxxxx
GetElementById () method
Definition: the getElementById () method returns a reference to the first object that owns the specified ID.
Return null if the element of ID is not specified
If there are multiple elements of the specified ID, the first one is returned
If you need to find elements that do not have ID, you can consider using querySelector () through the CSS selector
Syntax: document.getElementById (elementID)
Parameter value: String must be. The value of the element ID attribute.
Return value: element object specifies the element of ID
GetElementsByTagName () method
Definition: the getElementsByTagName () method returns a collection of objects with the specified signature
Tip: the parameter value "*" returns all elements of the document
Syntax: document.getElementsByTagName (tagname)
Parameter: String must get the tag name of the element
Return value: the NodeList object specifies the collection of elements for the signature
GetElementsByClassName () method
Definition: the getElementsByClassName () method returns a collection of all elements in the document with the specified class name as NodeList objects.
The NodeList object represents a sequential list of nodes. The NodeList object can access the nodes in the table through the node index number in the node list (the index number starts with 0).
Tip: you can use the length attribute of the NodeList object to determine the number of elements for a specified class name, and loop through each element to get the desired element.
Syntax: document.getElementsByClassName (classname)
Parameter: the element class name that String must get. Multiple class names are separated by spaces, such as "test demo"
Return value: NodeList object that represents the collection of elements with the specified class name. The order of elements in the collection is sorted by the order in which they appear in the code.
two。 Difference 2.1 getElement (s) Byxxxx gets dynamic collections, querySelector gets static collections
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 changes in the document.
Example 1:
Test 1 Test 2 Test 3 / get ul, in order to dynamically add li var ul = document.getElementById ('box'); / / get li var list = ul.getElementsByTagName (' li') in the existing ul; for (var I = 0; I)
< 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); JavaScript中 querySelector 与 getElementById 方法的区别_javascriptExample 2:
The static collection of the following code is reflected in the fact that after .querySelectorAll ('li') gets all the li in the ul, no matter how many li are dynamically added later, its parameters will not be affected.
Test 1 Test 2 Test 3 var ul = document.querySelector ('ul'); var list = ul.querySelectorAll (' li'); for (var I = 0; I < list.length; iTunes +) {ul.appendChild (document.createElement ('li'));} console.log (' list.length:',list.length); / / the output result is still 3, not the number of li at this time 6
The difference between querySelector and getElementById methods in JavaScript _ javascript_02
Why is it designed in this way?
The querySelectorAll method is clearly defined in the W3C specification:
The NodeList object returned by the querySelectorAll () method must be static ([DOM], section 8).
Let's take a look at what it looks like on Chrome:
Document.querySelectorAll ('a') .toString (); / / return "[object NodeList]" document.getElementsByTagName ('a') .toString (); / / return "[object HTMLCollection]"
HTMLCollection is defined in 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, HTMLCollection and NodeList are very similar in that they are a dynamic collection of elements, and each visit requires a re-query of the document.
Difference: HTMLCollection belongs to the Document Object Model HTML specification, while NodeList belongs to the Document Object Model Core specification.
This is a bit difficult to understand, but it would be easier to take a 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 nodes in the document, such as Element, Text, Comment, etc.
The HTMLCollection object contains only the Element nodes in the document
In addition, the HTMLCollection object provides one more namedItem method than the NodeList object
So in the browser, the return value of querySelectorAll is a static NodeList object, while the return value of the getElementsBy series is actually a HTMLCollection object.
2.2 different parameters are received
The parameter received by the querySelectorAll method is a CSS selector
The parameters received by the getElementsBy series can only be a single className, tagName and name
Var C1 = document.querySelectorAll ('.b1.c'); var c2 = document.getElementsByClassName ('c'); var c3 = document.getElementsByClassName ('b2') [0] .getElementsByClassName (' c')
Note: the parameters received by querySelectorAll must strictly conform to the CSS selector specification
The following way of writing will throw an exception (the element name, class, and ID in the CSS selector cannot start with a number).
Try {var e1 = document.getElementsByClassName ('1a2b3c'); 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 different browsers are compatible
QuerySelectorAll is supported by IE 8 +, FF 3.5 +, Safari 3.1 +, Chrome and Opera 10 +
GetElementsBy series, take getElementsByClassName in the specification as an example, IE 9 +, FF 3 +, Safari 3.1 +, Chrome and Opera 9 + are all supported
This is the end of the content of "what are the differences between querySelector and getElementById methods in JS". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.