Home > Web Front-end > JS Tutorial > body text

Detailed introduction to the native and powerful DOM selector querySelector (code attached)

亚连
Release: 2018-05-19 13:52:10
Original
1870 people have browsed it

This article mainly introduces some relevant knowledge about the native powerful DOM selector querySelector. Friends who need it can refer to it

In traditional JavaScript development, finding the DOM is often the first thing developers encounter. It’s a headache. There are not many DOM selection methods provided by native JavaScript. They are only limited to searching through tag, name, id, etc. This is obviously not enough. If you want to make a more precise selection, you must Don't use regular expressions that look very cumbersome, or use a library. In fact, all browser manufacturers now provide support for the querySelector and querySelectorAll methods. Even Microsoft has sent IE 8 as a representative to support this feature. querySelector and querySelectorAll serve as another way to find the DOM. It greatly facilitates developers. Using them, you can find the node you need as quickly as using CSS selectors.

The use of querySelector and querySelectorAll is very simple. As the title says, it is written exactly the same as CSS. For front-end developers, this is a learning experience with almost zero difficulty. If we have a p with an id of test, in order to get this element, you might do something like this:

document.getElementById("test");
Now let's do this Try using the new method to get this p:

document.querySelector("#test");
document.querySelectorAll("#test")[0];
Copy after login

The following is a small demonstration:

I am the p

with the id of test

I don’t think there is much difference, but if In a slightly more complicated situation, the original method will become very troublesome. At this time, the advantages of querySelector and querySelectorAll come into play. For example, in the following example, we will select the first sub-element p of the sub-element p of class p in the document. Of course, this is a mouthful, but using the new method in this article to select this element is better than describing it in words. Even simpler.

document.querySelector("p.test>p:first-child");
document.querySelectorAll("p.test>p:first-child")[0];
Copy after login

The following is a small demonstration:

I am the p tag in the layer

You should now have a very clear understanding of the parameters in the querySelector and querySelectorAll methods. Yes, it The parameters received are exactly the same as CSS selectors. The difference between querySelector and querySelectorAll is that querySelector is used to obtain one element, while querySelectorAll can obtain multiple elements. querySelector will return the first element matched, or Null if there is no matching element. querySelectorAll returns an array containing matched elements. If there are no matching elements, the returned array is empty. In the last example of this article, we use querySelectorAll to bold all elements with class emphasis.

var emphasisText = document.querySelectorAll(".emphasis");
for( var i = 0 , j = emphasisText.length ; i < j ; i++ ){
  emphasisText[i].style.fontWeight = "bold";
}
Copy after login

This is a native method, which is faster than jquery. The disadvantage is that IE6 and 7 do not support it.

W3C specification and implementation in 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. (Return the specified element The first one in the set that matches the selector in the node's subtree, if there is no match, returns null)

querySelectorAll: return a NodeList containing all of the matching Element nodes within the node's subtrees, in document order. If there are no such nodes, the method must return an empty NodeList. (Returns the set of nodes matching the selector in the subtree of the specified element node, using depth-first pre-search; if there is no match, this method returns an empty set)

There is no problem when BaseElement is a document, and the implementation of each browser is basically the same; however, when BaseElement is an ordinary dom Node (dom Node that supports these two methods), the browser's The implementation is a bit strange. For example:

<p class= "test"  id= "testId" > 
   <p><span>Test</span></p> 
</p> 
<script type= "text/javascript" >   
   var  testElement= document.getElementById( &#39;testId&#39; ); 
   var  element = testElement.querySelector( &#39;.test span&#39; ); 
   var  elementList = document.querySelectorAll( &#39;.test span&#39; ); 
   console.log(element); // <span>Test</span>
   console.log(elementList); // 1  
</script>
Copy after login

According to W3C understanding, this example should return: element: null; elementList: []; because there is no match for selectors in testElement as baseElement. node; but the browser seems to ignore baseElement and only cares about selectors, which means that baseElement is almost document at this time; this is inconsistent with our expected results. Maybe as browsers continue to upgrade, this issue will be unified!

Human wisdom is always infinite. Andrew Dupont invented a method to temporarily correct this strange problem, which is to specify the baseElement id in front of selectors to limit the matching range; this method is widely used in various In the popular framework;

Jquery implementation:

var  oldContext = context,
old = context.getAttribute( "id"  ),
nid = old || id,
Copy after login
try  {
	if  ( !relativeHierarchySelector || hasParent ) {
   	return  makeArray( context.querySelectorAll( "[id=&#39;"  + nid + "&#39;] "  + query ), extra );
 	}  
} 
catch (pseudoError) {} 
finally {
	if  ( !old ) {
	 	oldContext.removeAttribute( "id"  );
	}
}
Copy after login
### Let’s not look at other parts of this code, just look at how it implements this method; this code is from JQuery1.6 Fragment; when baseElement has no ID, set an id = "__sizzle__" for it, and then add it in front of selectors when using it to limit the range; context.querySelectorAll( "[id='" nid "'] " query; Finally, because this ID itself is not what baseElement should have, it needs to be removed: oldContext.removeAttribute( "id" );, Mootools implementation: ###
var  currentId = _context.getAttribute( &#39;id&#39; ), slickid = &#39;slickid__&#39; ;
_context.setAttribute( &#39;id&#39; , slickid);
_expression = &#39;#&#39;  + slickid + &#39; &#39;  + _expression;
context = _context.parentNode;
Copy after login

Mootools和Jquery类似:只不过slickid = 'slickid__';其实意义是一样的;方法兼容性:FF3.5+/IE8+/Chrome 1+/opera 10+/Safari 3.2+;IE 8 :不支持baseElement为object;

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

Node.Js实现端口重用步骤详解

js继承中的方法重写重点讲解

js方法的重写和重载的技巧详解

The above is the detailed content of Detailed introduction to the native and powerful DOM selector querySelector (code attached). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!