Tutorials Tonight's Logo

JavaScript querySelector Explained With Practical Examples


In this tutorial, you will learn about javascript querySelector, how to get an element using it in different cases with examples.

You already know that your DOM is a tree-like structure that is made up of all the elements of the webpage. You need to access these elements to read data or modify it in some way.

The querySelector is a method in javascript to select almost any element from the DOM.

querySelector JavaScript

Introduction to querySelector Method

querySelector is a javascript method which select the DOM element using CSS selector like p, h1, .class1, .class1 .class2, #id1, etc.

It returns the first element from the document that matched the specified selector or group of selectors. If no element is matched then it returns null.

let element = document.querySelector(selectors)

How querySelector search element in the DOM?

You know there are different types of search methods in computer science to search elements. The querySelector method uses depth-first pre-order traversal through the nodes of the document.

DOM tree

Depth-first means in the above example starting from html element it will go to its left to head then meta, not it's right which is the body.

pre-order means when at the body it will first check for itself then its first child, then second and so on.

Now let's see an example to get element by class using the querySelector method.


Get Element By Class

To select an element by class pass class name in the querySelector method preceding with a dot(.) as a string. Example querySelector(".class_name")

querySelector example

<body>
  <div class="box">
    <h3>Heading inside the 1st box.</h3>
    <p>This is a paragraph inside the <b>1st box</b>.</p>
  </div>
  <div class="box">
    <h3>Heading inside the 2nd box.</h3>
    <p>This is a paragraph inside the <b>2nd box</b>.</p>
  </div>

  <script>
    let element = document.querySelector(".box");
    element.style.background = "lightgreen";
  </script>
</body>

Output:

output 1

You can see how it selects only the first element that the CSS selector matches, other elements are untouched.


Get element by Id

To get an element by its id use hash (#) preceding with id name as a selector.

If select matches an id that is incorrectly used more than once then it returns the first element with a specified id.

Example

<body>
  <p id="id1">1st paragraph with id = id1</p>
  <p id="id1">2nd paragraph with id = id1 (incorrect use)</p>
  <button onclick="getElement()">Get element</button>

  <script>
    function getElement() {
      let element = document.querySelector("#id1");
      element.style.background = "lightgreen";
    }
  </script>

Output:

output 2

Get Element By Tag name

To select an element by its tag name pass use the querySelector method and pass the element's tag name as a string in the method. It will return the first element specified in the method.

Note: The tag name can be passed in any case capital, small or mixed.

Example

<body>
  <div>This is a div element.</div>
  <div>This is a div element.</div>

  <button onclick="getElement()">Get element by tag name</button>

  <script>
    function getElement() {
      let element = document.querySelector("div");
      element.style.background = "lightgreen";
    }
  </script>
</body>

Get element by attribute

There are many cases when you need to select elements from the document using the element's attribute.

To get a select element on the basis of its attribute value pass the attribute name wrapped in the square bracket as a selector in the querySelector method. Example querySelector("[title]") it select all element having title attribute.

Example1: get element by the title attribute

<body>
  <p title="1st item with title">querySelector selects and return only first element if selector matches.</p>
  <p title="2nd item with title">Paragraph with title.</p>
  
  <button onclick="getElement()">Get element with title attribute</button>

  <script>
    function getElement() {
      let element = document.querySelector("[title]");
      element.style.background = "lightgreen";
    }
  </script>
</body>

Here is another example to get an element by its attribute. In this example, we will select an anchor element on the basis of its target attribute.

Example2: get anchor element by the target attribute

<body>
  <a href="#">link without target attribute</a><br>
  <a href="#" target="_blank">1st link with target attribute</a><br>
  <a href="#" target="_blank">2nd link with target attribute</a><br>

  <button onclick="getElement()">Get element with target attribute</button>

  <script>
    function getElement() {
      let element = document.querySelector("[target]");
      element.style.border = "3px solid black";
    }
  </script>
</body>

Get element by attribute with the same value

To select an element by its attribute with a specific attribute value use the querySelector method and pass the attribute name and its value wrapped in a square bracket separated by an equal (=) sign. The attribute value is enclosed by quotes.

Example

<body>
  <p title="Some paragraph">My title is "Some paragraph".</p>
  <p title="A paragraph">My title is "A paragraph".</p>
  <p title="A paragraph">My title is "A paragraph".</p>

  <button onclick="getElement()">Get element with title attribute by value</button>

  <script>
    function getElement() {
      let element = document.querySelector('[title="A paragraph"]');
      element.style.background = "lightgreen";
    }
  </script>
</body>


Get Element By Group Selectors

Using querySelector you can use a very complex CSS selector to select the element in javascript. Every combination that is valid in CSS is also valid for this method.

Note: The querySelector method doesn't return any element for CSS pseudo-elements.

Let our HTML code be like this, and we want to select the 3rd list item of the 2nd container.

<div id="output">
  <div class="container">
    <ul>
      <li>List item 1</li>
      <li>List item 2</li>
      <li>List item 3</li>
      <li>List item 4</li>
    </ul>
  </div>
  <div class="container">
    <ul>
      <li>List item 1</li>
      <li>List item 2</li>
      <li>List item 3</li>
      <li>List item 4</li>
    </ul>
  </div>
</div>

Now to select 3rd list item of 2nd container, follow the steps below:

Example

let element = document.querySelector("#output>.container:nth-child(2) ul li:nth-child(3)");
element.style.background = "lightgreen";

Output:

output 3

Special Case: Get element whose class or id start with number

When you try to select an element with a class name or id starting with a number using the querySelector method, then it causes an error as an invalid selector.

<p id="1">Paragraph with id=1</p>
<script>
  let element = document.querySelector("#1");
  // error '#1' is not a valid selector
</script>
error selecting id starting with a number with querySelector

When the first character of an identifier is numeric then you need to escape it based on it's Unicode code point. For example, if the number is 5 whose Unicode value is U\0035, so to escape it use \35.

Example

<body>
  <div id="5">This is a div element with id=5</div>
  <button onclick="getElement()">Get element</button>

<script>
  function getElement() {
    // unicode of 5 is U\0035
    let element = document.querySelector("#\\35");
    // using double backslash to escape the escape character
    element.style.background = "lightgreen";
  }
</script>
</body>

There is also an alternate way to do this. Use class or id as attribute selector with its value.

Example

<body>
  <div id="5">This is a div element with id=5</div>
  <button onclick="getElement()">Get element</button>

  <script>
    function getElement() {
      let element = document.querySelector("[id='5']");
      element.style.background = "lightgreen";
    }
  </script>
</body>

Conclusion

In this section, we learn about the querySelector method, it's used and worked with many examples and selecting all kind of query, both simple and complex selectors.

Follow Us

Copyright © Tutorials Tonight. All Rights Are Reserved.