HomeAbout

Query Selector

querySelector

The Document method querySelector returns the first element within the document that matches the specified CSS selector, or group of CSS selectors.

  • If no matches are found, null is returned.

Simple Case:

// first matching <p> element const element = document.querySelector("p"); // first element with class="myclass" const element = document.querySelector(".myclass"); // first element with id="demo" // change text to "Hello World!" document.querySelector("#demo").innerHTML = "Hello World!";

Complex selector:

// first <input> element with the name="login" // located inside a <div> whose class is "user-panel main" // HTML <div class="user-panel main"> <input name="login"/> </div> // JS const element = document.querySelector("div.user-panel.main input[name='login']");

Use querySelectorAll() to fetch ALL matching elements.

AboutContact