[Label] [What is the difference between the Javasript]queryselectorall method compared to the Getelementsby series method?

Source: Internet
Author: User

Download: http://www.zhihu.com/question/24702250

Queryselectorall What's the difference compared to the following methods?

      • getElementsByTagName
      • Getelementsbyclassname
      • Getelementsbyname

1. The standard
Queryselectorall belongs to the selectors API specification [1]. [2] The Getelementsby series belongs to the DOM specification.

2. Browser-compatible
Queryselectorall has been well supported by IE 8+, FF 3.5+, Safari 3.1+, Chrome and Opera. The
Getelementsby series, with Getelementsbyclassname added to the specification at the latest, has been supported by IE +, FF 3 +, Safari 3.1+, Chrome, and Opera.

3. Receive Parameters
The Queryselectorall method receives a parameter that is a CSS selector. The Getelementsby series receives only a single classname, TagName, and name. The code is as follows [3]:

 var c1 = . Queryselectorall (c2 = document. Getelementsbyclassname ( ' C ' c3 = document. Getelementsbyclassname ( ' B2 ' ) [0 . getelementsbyclassname ( ' C '     

It is important to note that the parameters received by Queryselectorall must conform strictly to the CSS selector specification. So the following notation will throw an exception. The code is as follows [4]:

Try{VarE1=Document.Getelementsbyclassname(' 1A2B3C ');VarE2=Document.Queryselectorall('. 1a2b3c ');}Catch (e) {consoleerror (e. Message); }console. Log (e1 && e1[ 0classname); console. Log (e2 && e2[ 0classname            

(The element name, class, and ID in the CSS selector cannot begin with a number.) )

4. Return value
As most people know, Queryselectorall returns a Static node list, and the Getelementsby series returns a Live node list.
Take a look at the following classic example [5]:

Demo 1VarUl=Document.Queryselectorall(' UL ')[0],Lis=Ul.Queryselectorall("Li");For(VarI=0;I<Lis.Length;I++){Ul.AppendChild(Document.CreateElement("Li"));}Demo 2VarUl=Document.getElementsByTagName(' UL ')[0lis = ul.< Span class= "NX" >getelementsbytagname ( "li" for (var i = 0< Span class= "P"; i < lis. Length i++) {ul. Appendchild (document. Createelement ( "li"                /span>                

Because the LIS in Demo 2 is a dynamic Node List, every call to Lis will re-query the document, causing an infinite loop problem.
The LIS in Demo 1 is a static Node List, which is a snapshot of the Li Collection, and no action on the document will affect it.

But why design it like this?
In fact, the Queryselectorall method is clearly stipulated in the standard of the "6":

the NodeList object returned by the Queryselectorall () method must is static ([DOM], section 8). /c3>


So what is NodeList?
This is illustrated in the "7":

the NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining How this collection is implemented. NodeList objects in the DOM is live.

So, NodeList is essentially a dynamic Node collection, except that Queryselectorall has a definite requirement in the specification that it must return a static NodeList object.

Let's look at what's happening on Chrome:

document.querySelectorAll(‘a‘).toString(); // return "[object NodeList]"document.getElementsByTagName(‘a‘).toString(); // return "[object HTMLCollection]"

Here again a Htmlcollection object comes out, that htmlcollection is what?

The definition of htmlcollection is as follows [8]:

An htmlcollection is a list of nodes. An individual node is accessed by either ordinal index or the node ' s name or ID attributes.
Note:collections in the HTML DOM is assumed to being live meaning that they is automatically updated when the underlying D Ocument is changed.


In fact, htmlcollection and NodeList are very similar and are a dynamic collection of elements that need to be re-queried for each visit. The fundamental difference between the two is that htmlcollection belongs to the Document Object Model HTML specification, and NodeList belongs to Document Object Mo Del Core specification.
This is a bit difficult to understand, see the following example will be better understand [9]:

VarUl=Document.getElementsByTagName(' UL ')[0],Lis1=Ulchildnodeslis2 = 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, Comment, and so on.
The Htmlcollection object will only contain Element nodes in the document.
In addition, the Htmlcollection object provides a Nameditem method more than the NodeList object.

So in modern browsers, the return value of Queryselectorall is a static NodeList object, and the return value of the Getelementsby series is actually a Htmlcollection object.



[1]Selectors API Level 2
[2]Document Object Model Core
[3]http/jsbin.com/cuduyigi/1/edit?html,js,console
[4]http/jsbin.com/mabefihi/1/watch?html,js,console
[5]
Demo 1:/ httpjsbin.com/daduziba/1/watch?html,js,output
Demo 2:/ httpjsbin.com/xuvodipo/1/watch?html,js,output
[6] Selectors API Level 2
[7] Document Object Model Core
[8] Document Object Model HTML
[9] http/jsbin.com/qijivove/1/watch?html,js,console


Getelementbyid/queryselector the two obtained are DOM nodes, the result is no different.

The real-time nature of getelement* is reflected in the return of the collection, we know that getelementsby* and Queryselectorall return is a collection of nodes, similar to the array, the difference between the two methods is whether the collection will automatically update.

//初始时DOMain中没有元素x = document.querySelectorAll(‘img‘)y = document.getElementsByTagName(‘img‘)document.body.appendChild(new Image())x.length // 0y.length // 1


In addition, getElementById this can only be used on document, because the ID is the only one under normal circumstances.

It says a lot about the difference between the implementation and the principle of Queryselectorall and Getelementsby , and here I take the data to talk and see the difference in performance.

All tests come from http:// jsperf.com/getelementsby-vs-queryselectorall/7, and interested friends can try them on their own.

    • Hardware environment: Core i5-3570 3.40GHz, Win7 64bit



    • Data format: [Ops/sec] Method

ops/sec refers to the number of times per second that the operation is performed , the higher the better.

    • Browser 1:chrome 37.0.2062.68 32-bit
[-20,989,532] document.getElementsByTagName(‘a‘);[----166,170] document.querySelectorAll(‘a‘);[-27,659,047] document.getElementsByName(‘name‘);[-----79,022] document.querySelectorAll(‘[name=name]‘);[-22,972,151] document.getElementsByClassName(‘classname‘);[-----67,003] document.querySelectorAll(‘[class = classname]‘);

Reviews:
The Getelementby
series is basically 100+ times faster than Queryselectorall .


    • Browser 2:firefox 31.0 32-bit
[226,165,531] document.getElementsByTagName(‘a‘);[----144,576] document.querySelectorAll(‘a‘);[-10,197,651] document.getElementsByName(‘name‘);[----119,340] document.querySelectorAll(‘[name=name]‘);[227,034,307] document.getElementsByClassName(‘classname‘);[----104,720] document.querySelectorAll(‘[class = classname]‘);

Reviews:
Firefox on getElementsByTagName and getelementsbyclassname than chrome 10 times times faster, while the remaining four are similar, there are high-skilled to analyze the reason?


    • Browser 3:ie 11.0.9600
[--1,797,107] document.getElementsByTagName(‘a‘);[-----59,829] document.querySelectorAll(‘a‘);[--1,344,551] document.getElementsByName(‘name‘);[-----13,706] document.querySelectorAll(‘[name=name]‘);[--1,710,804] document.getElementsByClassName(‘classname‘);[------8,938] document.querySelectorAll(‘[class = classname]‘);

Reviews:
IE is much slower than FF and Chrome. But it doesn't matter: the speed is not enough, the feelings to gather.

is mainly the difference between the selector and whether it is real-time .

1. Selector

    • queryselector**

Queryselector and Queryselectorall are the newly introduced HTML5 features like jquery's selector. The former returns the first element of the matching selector in the subtree that returns the specified element node in document order, and no returns NULL. The latter returns a collection of elements in the subtree that return the specified element node in document order, matching the selector, if there is no match returned by an empty collection. Take Queryselectorall as an example to illustrate.
Queryselectorall (' selectors '), where selectors can contain multiple CSS selectors, either a class selector or an ID selector, or a tag type selector, or it can be a mixture of them. as

elements = document.querySelectorAll(‘div.foo‘);//返回所有带foo类样式的div
    • getelementsby***

getelementsby*** can only be found based on specific selectors . The getElementById (ID) selector content is the ID name that returns the object reference that has the first ID. For example, there is a
<div id= "No1" ><div> elements. can be obtained with Queryselector ('#No1 ') or getElementById (' No1 '). The selector of the getElementsByTagName selector is the Name property value of the tag, and the selector of the Getelementsbyclassname is the class name, which is written directly, without adding #, . etc. identifiers.

2. Real-time sex
queryselector** returns the non-real-time. And the getelementby** returns are real-time.
Use the following example to illustrate:

<div id="container">    <div></div>    <div></div></div>
First select the element with ID container in the pageContainer=Document.getElementById(' #container ');console. Log (container. Childnodes. Length) //result 2//then add a child element to it by code container< Span class= "P". appendchild (document. Createelement ( ' div '  This element is not only added to the page, the variable container is also automatically updated console. (container. Childnodes. Length) //result 3           

The results of the Getelementby are found to return real-time results, and if used queryselector, the result is the original structure returned.

[Label] [What is the difference between the Javasript]queryselectorall method compared to the Getelementsby series method?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.