What is the querySelector?

What is the querySelector method in Javascript and how to use it?

The querySelector helps you to find first first element that matches css selector you specify. So basically it lets you find html elements.

const header = document.querySelector("h1");
You can also use # (hash means id).
const myid = document.querySelector("#myid");

To search a class use a dot.

const myClass = document.querySelector(".class");

queryselector javascript

How to use the querySelector() method

    • The querySelector() method takes a CSS selector as its argument and returns the first element that matches the selector.
    • The CSS selector can be a tag name, an ID, or a class name.
    • For example, the following code will get the first h1 element on the page:
const header = document.querySelector("h1");
  • The querySelector() method can also be used to get multiple elements that match a selector. To do this, you can use the querySelectorAll() method.

Leave a Reply

Your email address will not be published. Required fields are marked *