Introducing querySelector() and querySelectorAll() on elements in JavaScript

Introducing querySelector() and querySelectorAll() on elements in JavaScript

I recently learnt about JavaScript so thought why not share my learnings?

I will share how to use the JavaScript querySelector() and querySelectorAll() to find elements based on CSS selectors.

querySelector()

querySelector() is a function that returns an element that matches a CSS selector. Note the querySelector() method only returns the first instance of a selector.

If no matches are found, null is returned.

Let's see how we use querySelector() to select a element in DOM. Select a input field, where the input is given by user and it has an id input-given. We have to select the input element by CSS id-selector.

let userInput = document.querySelector("#input-given");

Assume, there is a button tag which has class submit-btn, we have to select the button element by CSS class-selector.

let submitBtn = document.querySelector(".submit-btn");

querySelectorAll()

querySelectorAll() method, which is defined both on the document object and on element nodes, takes a selector string and returns a NodeList containing all the elements that it matches CSS Selector.

If no element matches, it returns an empty NodeList.

Let's assume there are three input fields for angles of triangle.

<!DOCTYPE html>
<html>
  <body>
    <div>
      <input type="number" class="angles-input" />
      <input type="number" class="angles-input" />
      <input type="number" class="angles-input" />
    </div>
  </body>
</html>

So, We have to select all input fields using CSS class-selector and querySelectorAll() returns a NodeList containing all three input elements.

let inputAngles = document.querySelectorAll(".angles-input");

Hope this post provides you enough interest to use querySelector and querySelectorAll next time you work on DOM manipulation.

If you liked my content, connect with me?

github
linkedin
twitter