Javascript Tutorial: querySelector () method,

Source: Internet
Author: User

Javascript Tutorial: querySelector () method,

Module dom {
[Supplemental, NoInterfaceObject]
Interface NodeSelector {
Element querySelector (in DOMString selectors );
NodeList querySelectorAll (in DOMString selectors );
};
Document implements NodeSelector;
DocumentFragment implements NodeSelector;
Element implements NodeSelector;
};

From the interface definition, we can see that Document, DocumentFragment, and Element all implement the NodeSelector interface. That is, all three types of elements have two methods. The parameters of querySelector and querySelectorAll must be a string that conforms to css selector. The difference is that querySelector returns an object, and querySelectorAll returns a set (NodeList ). Well-developed 5-year UI front-end framework!

CurrentlyIE8/9 and Firefox/Chrome/Safari/OperaThey are supported by the latest version.

 

 

The querySelector () method accepts a CSS query and returns the first child element of the matching mode. If no matching element exists, null is returned. See the following example:

// Obtain the body element varbody = document. querySelector ("body"); // obtain the element varmyDiv = document whose ID is myDiv. querySelecotr ("# myDiv"); // obtain the first element containing the class selected varselected = document. querySelector (". selected "); // obtain the first image element containing a button class
 

  
Varimg = document. body. querySelector ("img. button"); when the querySelector () method applies the Document type, it tries to match the pattern from the document element. If the application is of the Element type, the query will only try to find a match from the child node of the Element.
  
CSS queries can be complicated or simplified as needed. If the query contains a syntax error or does not support selector, querySelector () or throws an error. Well-developed 5-year UI front-end framework!
  
The querySelector () method also accepts the optional second parameter, which is a namespace parser. It is a function that accepts a namespace prefix and returns its related URI, similar:

Varnsresolver = function (prefix) {switch (prefix) {case "w3cmm": return "http://www.w3cmm.com"; // other code here }};
 


  
The namespace parser is useful for executing queries in XHTML documents embedded with other languages such as SVG or MathML, as is the case with XML documents. The namespace in the CSS query is specified using a pipe, as shown below:

varsvgImage=document.querySelector("svg|svg",function(prefix){   switch(prefix){   case:"svg":   return"http://www.w3.rog/2000/svg";   }   });
 


  
In this example, the first svg image is returned by searching the element defined as <svg: SVG> in the document. When an svg namespace prefix is encountered in the query, the namespace parser function is called to determine the URI. If there is no namespace parser, an error is thrown because the query engine cannot identify the prefix of the svg namespace.
Well-developed 5-year UI front-end framework!
Implementation differences between querySelector and querySelectorAll in different browsers

To obtain the elements whose class attribute is "red. getElementsByClassName ('red') can also use document. querySelector ('. red') and document. querySelectorAll ('. red ').

However, the implementation of Element. querySelector and Element. querySelectorAll is incorrect, as shown below:

<div id="d1">     <p><a href=http://www.jcodecraeer.com>SINA</a></p> </div> <script type="text/javascript">        function $(id){return document.getElementById(id);}     var d1 = $('d1');     var obj1 = d1.querySelector('div a');     var obj2 = d1.querySelectorAll('div a');     alert(obj1); // -> http://www.jcodecraeer.com     alert(obj2.length); // -> 1   </script>
 

In the browser that supports these two methods, "http://www.sina.com.cn/#,and" 1 "are displayed ". Indicates that the desired element or element set is queried. This is not consistent with W3C definition. The definition should look for "div a" in the element d1 range, but there is no div in d1. Therefore, null and empty sets should be returned respectively.

In jQuery1.4.2 and earlier versions, only document. querySelectorAll is used, and Element. querySelectorAll is not used. After jQuery1.4.3, Element. querySelectorAll is used, but fixed. Add "#__ sizzle _" before the selector to force it to search for the specified Element (3903-3918 rows ). Simplify the 5-year UI front-end framework!

function $(id){return document.getElementById(id);} var d1 = $('d1'); var obj1 = d1.querySelector('div a'); var obj2 = d1.querySelectorAll('div a'); var old = d1.id, id = d1.id = "__sizzle__"; try {     var query = '#' + id + ' div a';     alert(d1.querySelector( query ));     alert(d1.querySelectorAll( query ).length); } catch(e) { } finally {     old ? d1.id = old : d1.removeAttribute( "id" ); }
 


The implementation is clever. If an element of the specified range has an id, it is retained in the old, "_ sizzle _" to assign a value to it as a temporary id, specify the search range as "#__ sizzle _" before the selector "div a", that is, d1. Finally statement. If the element in the specified range has an id, It is restored to old. If no value exists, the temporary id attribute "_ sizzle _" is removed __".

 


What is documentquerySelectorAll () in JavaScript?

Document. querySelectorAll () is a new method introduced in html5. it is used in the same way as jQuery selector.
For example:
Document. querySelectorAll ("div ");
Document. querySelectorAll (". comment ");
Document. querySelectorAll ("# userid ");

Because it is a native method of HTML5, jQuery reference is not required.

We recommend that you learn the best javascript books or tutorials.

The JavaScript authoritative guide (version 4) is the best JavaScript book.

The JavaScript authoritative guide comprehensively introduces the core of the JavaScript language and the legacy and standard DOM implemented in Web browsers. It uses some complex examples to illustrate how to process verification form data, use cookies, create portable DHTML animations, and other common tasks. This book also includes a detailed reference manual, covering the core APIs of JavaScript, legacy client APIs, and W3C standard DOM APIs, describes every JavaScript Object, method, nature, constructor, constant, and event handler in these Apis.

Online shop prices (starting from 68.8 RMB... the first step is clearly explained. The reference manual later is poorly organized, especially for the third, fourth, and fifth parts.

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.