DOM Queryselector Selector

Source: Internet
Author: User
Tags mootools

Native powerful Dom Selector queryselector

In traditional JavaScript development, finding the DOM is often the first headache that developers encounter, and native JavaScript does not provide much of a DOM selection, only limited to finding it through tags, name, id, and so on, which is obviously far from enough if you want to enter A more precise choice of rows would have to use a regular expression that looks very cumbersome, or use a library. In fact, all browser vendors now offer support for both Queryselector and Queryselectorall, and even Microsoft has deployed IE 8 as a proxy for this feature, Queryselector and Queryselectorall, as another way to find the DOM, is great for developers, and you can use them as quickly as possible to find the nodes you need, just as you would with CSS selectors.

The use of Queryselector and Queryselectorall is very simple, as the title says, it is exactly the same as the CSS, and for front-end developers, this is a learning curve that is almost zero. If we have a DIV with ID test, in order to get to this element, you might look like this:

document.getElementById ("test");

Now let's try using the new method to get the DIV:

Document.queryselector ("#test");d ocument.queryselectorall ("#test") [0];

Here's a small demo:

I'm a div with ID test

The difference is not very good, but if it is slightly more complicated, the original method will become very troublesome, at this time the advantages of Queryselector and Queryselectorall play out. For example, in the following example, we will select the first child element p of the div of class test in document, which is very awkward, but it is simpler to use this new method to select this element than to describe it in words.

Document.queryselector ("Div.test>p:first-child");d ocument.queryselectorall ("Div.test>p:first-child") [0];

Here's a small demo:

I'm the P tag in the layer.

It should now be clear to the parameters in the Queryselector, Queryselectorall method, yes, it receives the same parameters as the CSS selector. The difference between Queryselector and Queryselectorall is that queryselector is used to get an element, and Queryselectorall can get multiple elements. Queryselector returns the first element that matches to, or Null if there are no matching elements. Queryselectorall returns an array that contains the matching elements, and if there are no matching elements, the returned array is empty. In the last example of this article, we use Queryselectorall to show all elements of class emphasis as bold.

var emphasistext = Document.queryselectorall (". emphasis"); for (var i = 0, j = emphasistext.length; I < J; i++) {
   
    emphasistext[i].style.fontweight = "Bold";}
   

This is the native method, compared to the speed of jquery, the disadvantage is IE6, 7 does not support.

The specification and the realization of the library

Queryselector:return the first matching Element node within the node ' s subtrees. If there is no such node, the method must return NULL. (returns the first of the set of matching selector in the subtree of the specified element node, and returns null if there is no match)

Queryselectorall:return a NodeList containing all of the matching Element nodes within the node ' s subtrees, in document or Der. If There is no such nodes, the method must return an empty NodeList. (Returns a collection of nodes that match selector in the subtree of the specified element node, using a depth-first lookup; If there is no match, this method returns an empty collection)

This is not a problem when baseelement for document, the implementation of the browsers is basically consistent, but when BaseElement is a normal DOM node (which supports both methods of DOM node), the implementation of the browser is a bit strange, As an example:

<div class= "test"   id= "TestID" >      <p><span>Test</span></p> </div> < Script type= "Text/javascript" >          var   testelement= document.getElementById (' TestID ');       var   element = Testelement.queryselector ('. test span ');       var   elementlist = Document.queryselectorall ('. test span ');       Console.log (element);  <span>Test</span>     Console.log (elementlist);  1    </script>

According to the element:null;elementlist:[, this example should return: "Because there is no matching sub-node in the BaseElement testelement that matches selectors But the browser seems to ignore the baseelement, only care about selectors, which means that at this time baseelement near document; This is not what we expected, and perhaps with the escalating browser, this problem will be stick!

Man's wisdom is always endless, Andrew DuPont invented a method to temporarily fix this strange problem, that is, in front of the selectors to specify the BaseElement ID, limit the range of matching; This method is widely used in various popular frameworks;

The implementation of jquery:

var   oldcontext = Context,old = Context.getattribute (  "id"   ), nid = Old | | ID,
Try   {if   (!relativehierarchyselector | | hasparent) {     return   Makearray (Context.queryselectorall (  "[id= '"   + nid +  "']"   + query), extra);  }    }  catch (Pseudoerror) {} finally {if   (!old) {Oldcontext.removeattribute (  "id"   );}}

Let's not look at the rest of the code, just see how he does it; This code is a fragment of JQuery1.6, and when BaseElement has no ID, set an id = "__sizzle__" and then use it in front of selectors. Context.queryselectorall ("[id= '" + nid + "']" + query; Finally, because the ID itself is not baseelement should have, so, Also need to remove: Oldcontext.removeattribute ("id"); , the implementation of MooTools:

var   currentid = _context.getattribute (' id '), Slickid =  ' slickid__ '; _context.setattribute (' id ', slickid); _ expression =  ' # '   + slickid +  '   + _expression;context = _context.parentnode;

MooTools and jquery are similar: just slickid = ' slickid__ '; in fact the meaning is the same; Method compatibility: Ff3.5+/ie8+/chrome 1+/opera 10+/safari 3.2+;ie 8 : BaseElement is not supported as object;

This article address: http://www.nowamagic.net/librarys/veda/detail/388, Welcome to visit the original source.

DOM Queryselector Selector

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.