Mastering JavaScript DOM
About Lesson

Select Single Element / querySelector / getElementById

The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.

Syntax

element = document.querySelector(selectors);

Parameters

selectors
DOMString containing one or more selectors to match. This string must be a valid CSS selector string; if it isn’t, a SYNTAX_ERR exception is thrown. 

Return value

An HTMLElement object representing the first element in the document that matches the specified set of CSS selectors, or null is returned if there are no matches.

If you need a list of all elements matching the specified selectors, you should use querySelectorAll() instead.

Example

Let’s grab the button element with an id of “btnSubmit” and attach a click handler to it.  (we will learn more about attaching events shortly).  

However, not here, as we are using CSS selectors as parameter to the querySelector function, for ID, we are prefixing it with “#” symbol.

const btnSubmit = document.querySelector("#btnSubmit");
btnSubmit.addEventListener("click", (e) => {
  e.preventDefault();
  alert("Awesome!");
});

So, when you click the button and alert should be displayed.

We can also use getElementById to select any HTML element by it’s identifier.

// We can also use the below method to select element by ID
const rootElement = document.getElementById("root");
console.log("rootElement: ", rootElement);

NOTE: Here we don’t prefix the ID with ‘#’.

Hands on Exercise

Try out the code by clicking this link

0% Complete