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

document.querySelector('css_selector')

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>

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

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

document.querySelector('.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.

 

Reference:

 

ChristianKovats
ChristianKovats

Christian Kovats is a London-based web designer who loves crafting innovative and user-friendly interfaces. His passion for design is only rivaled by his love for nature and hiking, often drawing inspiration from his treks through the diverse landscapes of the UK. Outside of work, Christian enjoys spending quality time with his wife and 4-year-old son. A seasoned lucid dreamer, he also spends time exploring the intricate world of dream interpretation, reflecting his ever-curious and creative mind.

ChristianKovats

Leave a reply

You must be logged in to post a comment.