Tutorials Tonight
Follow Us

JavaScript querySelector Explained With Examples


In this tutorial, you will learn about the Javascript querySelector method in detail. You will learn how to select elements from DOM using the querySelector method with a CSS selector.

You already know that the DOM is a tree-like structure that is made up of all the elements of the webpage.

To modify, add, remove or replace these elements first you need to access these elements. JavaScript provides multiple methods to access these elements.

One such method is the querySelector method in javascript. It can be used to select almost any element from the DOM.

querySelector JavaScript

These are the list of concepts covered in this article:

    Table of contents

  1. Introduction to Javascript querySelector
    1. How querySelector search elements
  2. Select Element By Class
  3. Select Element By Id
  4. Select Element By Tag name
  5. Select Element By attribute
  6. Select Element By attribute value
  7. Select Element By group selector
  8. Special case

Introduction JavaScript querySelector

JavaScript querySelector method is used to select elements from the DOM (from the webpage). It returns the 1st match element.

querySelector uses CSS selector like p, h1, .class1, .class1 > span, #id1, etc to select the element from the DOM.

If the targeted element exists in the DOM, it will return the 1st match from the DOM, if not it will return null.

Syntax:

document.querySelector(selector);

Here selector is a valid CSS selector.


How querySelector search elements?

DOM has a tree-like structure and querySelector finds the desired element from it. To find the element, it traverses the DOM tree and finds the element from the tree.

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 goes to child node 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.


Select Element By Class

The querySelector uses a CSS selector to select the element. CSS selector to select an element by class is .class1.

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

The following example will select the element with class class1.

querySelector example

<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>
  // selecting element by class
  let element = document.querySelector(".box");

  element.style.background = "lightgreen";
</script>

Output:

output 1

You can see in the above example there are 2 elements with the class box but only the first element is selected and highlighted.


Select element by Id

To select an element by its id use the hash # symbol preceding with id name as a selector. For example querySelector("#id_name").

If the targeted element with id exists in the DOM then the 1st matching element will be returned (however id should be unique not 2 or more elements should have the same id).

Example

<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() {
    // selecting element by its id
    let element = document.querySelector("#id1");

    element.style.background = "lightgreen";
  }
</script>

Output:

output 2

Select Element By Tag name

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

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

Example

<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>

Select 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

<p title="1st item with title">Paragraph with 1st title.</p>
<p title="2nd item with title">Paragraph with 2nd title.</p>
<button onclick="getElement()">Get element with title attribute</button>

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

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

<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>

Select 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

<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>

Get Element By Group Selectors

Using querySelector you can apply 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 the 3rd list item of the 2nd container, follow the steps below:

  1. first, select output id by "#output"
  2. Then select container class inside it by "#output>.container"
  3. Then select its 2nd container child by "#output>.container:nth-child(2)"
  4. Then select unorderd list inside it by "#output>.container:nth-child(2) ul"
  5. Now select list item inside it by "#output>.container:nth-child(2) ul li"
  6. Finally select 3rd list item by "#output>.container:nth-child(2) ul li:nth-child(3)"

Example

// selecting 3rd list item of 2nd container
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 JavaScript querySelector method, it's used and worked with many examples and selecting all kinds of queries, both simple and complex selectors.