This is the 21st day of my participation in the August More Text Challenge

Understand the Selectors API

The Selectors API is a CSS Selectors based matching mode for retrieving DOM elements. JQuery has long used CSS Selectors to query DOM elements for references. The three methods commonly used by Selectors are querySelector(),querySelectorAll(), and matches().

querySelector()

QuerySelector (), which takes an argument, returns an element in the document that matches the specified CSS selector. Returns null if any matches are found.

<body> <p class="username"> I am Jackson </p> </body> <script> let body = document.querySelector('body'); console.log(body); let username = document.querySelector('.username'); console.log(username); </script>Copy the code

When we use this method on document, we search from the document element. You can’t add special selectors in this way, or it will make an error.

querySelectorAll()

This method is the same as the querySelector method, except that the query matches all nodes, not one, and returns an instance of NodeList. It’s pretty much a static snapshot form and doesn’t really query at the bottom of Inrush.

    let spans = document.querySelectorAll('span');
    console.log(spans);
Copy the code

I didn’t write the SPAN tag here, but it does return an instance of NodeList.

matches()

The matches() method takes a CSS selector argument that checks whether there is a match and returns true if there is, or false if there is not.

    let body = document.body.matches('body');
    console.log(body);//true
Copy the code

Here we have a method that looks for the body element, which must return true, so we can use this method to determine if there is a body element and do something else. It is often associated with if.

Element traversal tips

Previous versions of IE9 did not treat Spaces between elements as empty nodes, as other browsers do, resulting in differences in properties such as childNodes and firstChild. So the W3c has defined a new set of attributes.

The Element Traversal API adds five attributes to the DOM Element:

ChildElementCount, which returns the number of child elements (excluding text nodes and comments);

FirstElementChild, pointing to the child of the firstElement type (Element version firstChild);

LastElementChild, which refers to the lastElementChild (Element version lastChild);

PreviousElementSibling refers to the sibling of the previousElement type (Element version previousSibling);

NextElementSibling, points to the sibling of the latter Element type (Element version nextSibling).

In supported browsers, all DOM elements have these attributes to facilitate traversal of DOM elements. This way developers don’t have to worry about blank text nodes.