DOM querySelector and querySelectorAll

Hi, in this post I’m going to explain you how the querySelector and querySelectorAll works.

This HTML is to show you how these methods works:

<html>
    <head>
        <title>By Cristina Rojas</title>
        <link rel = "stylesheet"
        type = "text/css"
        href = "styles.css" />
    </head>
    <body>
        <h1>DOM - Cristina Rojas</h1>

        <ul id="list" class="list">
            <li>item 1</li>
            <li>item 2</li>
            <li>item 3</li>
            <li>item 4</li>
            <li>item 5</li>
        </ul>

        <script src="dom1.js"></script>
    </body>
</html>

.querySelector(‘ ‘)

To get the element that is in the DOM, in this case the querySelector(”) will get the first element in the document and the syntax is:

document.querySelector('htmlTag');// could be htmlTag, .class, #id

Examples of use:

  • If you just have the element (not class, no id) then you need to insert the html tag name inside the parenthesis
let ulElementQuerySelectorByTag = document.querySelector('ul');      // <ul id="list" class="list">...</ul> element
  • If you have the class in the element then you can insert the class name inside the parenthesis
let ulElementQuerySelectorByClass = document.querySelector('.list');  // <ul id="list" class="list">...</ul> element
  • If you have the id of the element then you can insert the id name inside the parenthesis
let ulElementQuerySelectorById = document.querySelector('#list');    // <ul id="list" class="list">...</ul> element

Result:

.querySelectorAll(”)

This method returns all elements in the document that matches. The format of the return is a static NodeList object.

Examples of use:

  • If you just have the element (not class, no id) then you need to insert the html tag name inside the parenthesis
let ulElementQuerySelectorAllByTag = document.querySelectorAll('ul');      // NodeList [ul#list.list] 
  • If you have the class in the element then you can insert the class name inside the parenthesis
let ulElementQuerySelectorAllByClass = document.querySelectorAll('.list'); // NodeList [ul#list.list]
  • If you have the id of the element then you can insert the id name inside the parenthesis
let ulElementQuerySelectorAllById = document.querySelectorAll('#list');    // NodeList [ul#list.list]

Result:

By Cristina Rojas.