Register Now


Lost Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Javascript querySelector

Javascript querySelector

When we want to select or access one individual element on a page, we can use the querySelector() method. It returns the first element node that matches the CSS selector(s) we need. If we want to return all elemets, we need to use the querySelectorAll method.

The syntax


For a simple example, we will use this HTMl content

<div class="content">
<h2>This is a test heading</h2>
<p class="description">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea rem consequatur maxime nesciunt dignissimos!</p>
<p>Just some other paragraph</p>

<li>List 1</li>
<li>List 2</li>
<li>List 3</li>
<li>List 4</li>

To get the first element that has the class “content”


The method takes a parameter which must be a valid CSS selector. If the parameter is incorrect, a syntax error is thrown. For example:

document.querySelector('.contentt').style.backgroundColor = "red";

Because the CSS selector is incorrect we get the following error in the console:

Uncaught TypeError: Cannot read properties of null (reading 'style')

We can access HTML elements like this:

document.querySelector('h2').style.color = "red";

This will change the color of the first h2 element to red. If you had more than one h2 elements on this page, those text color would not be affected.

We can access an HTML element with a specific class:

document.querySelector('p.description').style.color = "red";

This will change the text color of the paragraph element that has the class “description”.

We can use more complex selectors as well:

document.querySelector('div ul li:last-child').style.color = "red";

This will change the text color of the last list item in the unordered list.

The querySelector method is similar to the getElementById method in that they both return a single element node.



Leave a reply