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];
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];
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"; }
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( '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 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,
try { if ( !relativeHierarchySelector || hasParent ) { return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); } } catch (pseudoError) {} finally { if ( !old ) { oldContext.removeAttribute( "id" ); } }
var currentId = _context.getAttribute( 'id' ), slickid = 'slickid__' ; _context.setAttribute( 'id' , slickid); _expression = '#' + slickid + ' ' + _expression; context = _context.parentNode;
Mootools和Jquery类似:只不过slickid = 'slickid__';其实意义是一样的;方法兼容性:FF3.5+/IE8+/Chrome 1+/opera 10+/Safari 3.2+;IE 8 :不支持baseElement为object;
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
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!