Back to Home

Searching: getElement*, querySelector*

DOM navigation properties are great when elements are close to each other. What if they are not? How to get an arbitrary element of the page? There are additional searching methods for that.

document.getElementById or just id

If an element has the id attribute, we can get the element using the method document.getElementById(id), no matter where it is. For instance: Also, there’s a global variable named by id that references the element: …That’s unless we declare a JavaScript variable with the same name, then it takes precedence:

querySelectorAll [#querySelectorAll]

By far, the most versatile method, elem.querySelectorAll(css) returns all elements inside elem matching the given CSS selector. Here we look for all

  • elements that are last children: This method is indeed powerful, because any CSS selector can be used.

    querySelector [#querySelector]

    The call to elem.querySelector(css) returns the first element for the given CSS selector. In other words, the result is the same as elem.querySelectorAll(css)[0], but the latter is looking for all elements and picking one, while elem.querySelector just looks for one. So it’s faster and also shorter to write.

    matches

    Previous methods were searching the DOM. The elem.matches(css) does not look for anything, it merely checks if elem matches the given CSS-selector. It returns true or false. The method comes in handy when we are iterating over elements (like in an array or something) and trying to filter out those that interest us. For instance:

    closest

    Ancestors of an element are: parent, the parent of parent, its parent and so on. The ancestors together form the chain of parents from the element to the top. The method elem.closest(css) looks for the nearest ancestor that matches the CSS-selector. The elem itself is also included in the search. In other words, the method closest goes up from the element and checks each of parents. If it matches the selector, then the search stops, and the ancestor is returned. For instance:

    getElementsBy*

    There are also other methods to look for nodes by a tag, class, etc. Today, they are mostly history, as querySelector is more powerful and shorter to write. So here we cover them mainly for completeness, while you can still find them in the old scripts. - elem.getElementsByTagName(tag) looks for elements with the given tag and returns the collection of them. The tag parameter can also be a star “*” for “any tags”. - elem.getElementsByClassName(className) returns elements that have the given CSS class. - document.getElementsByName(name) returns elements with the given name attribute, document-wide. Very rarely used. For instance: Let’s find all input tags inside the table: // doesn’t work document.getElementsByTagName(‘input’).value = 5; // should work (if there’s an input) document.getElementsByTagName(‘input’)[0].value = 5; Looking for .article elements:

    Live collections

    All methods “getElementsBy” return a live* collection. Such collections always reflect the current state of the document and “auto-update” when it changes. In the example below, there are two scripts. 1. The first one creates a reference to the collection of

    . As of now, its length is 1. 2. The second scripts runs after the browser meets one more
    , so its length is 2. In contrast, querySelectorAll returns a static collection. It’s like a fixed array of elements. If we use it instead, then both scripts output 1: Now we can easily see the difference. The static collection did not increase after the appearance of a new div in the document.

    Summary

    There are 6 main methods to search for nodes in DOM:

    Method Searches by… Can call on an element? Live?
    querySelector CSS-selector -
    querySelectorAll CSS-selector -
    getElementById id - -
    getElementsByName name -
    getElementsByTagName tag or
    getElementsByClassName class
    By far the most used are querySelector and querySelectorAll, but getElement(s)By can be sporadically helpful or found in the old scripts. Besides that: - There is elem.matches(css) to check if elem matches the given CSS selector. - There is elem.closest(css) to look for the nearest ancestor that matches the given CSS-selector. The elem itself is also checked. And let’s mention one more method here to check for the child-parent relationship, as it’s sometimes useful: - elemA.contains(elemB) returns true if elemB is inside elemA (a descendant of elemA) or when elemA==elemB.

    <div id="elem">
      <div id="elem-content">Element</div>
    </div>
    
    <script>
      // get the element
    *!*
      let elem = document.getElementById('elem');
    */!*
    
      // make its background red
      elem.style.background = 'red';
    </script>
    Example:

    Follow the lesson from Microsoft Web-Dev-For-Beginners course

    Tags: web,development