Tuesday , 18 June 2019
Home / Programming / JavaScript / Selectors API – Advanced JavaScript Tutorial
Selectors API
Selectors API

Selectors API – Advanced JavaScript Tutorial

The selectors API is a simpler way to grab elements by using CSS queries. If you recall, you can change the styles of an element using CSS. Here’s an example of how you would do so.

To grab an element in general, you just type in the tag name. To grab an element with an ID, you type a hash tag followed by the ID name. For classes, you type a period before the class name. Lastly, you can also have complex queries like our last example. It grabs all p tags with the class Style3.

All these are CSS queries. With the selectors API, you can use CSS queries to grab elements in JavaScript. Let’s update the <body> tags in the HTML document to this.

These are just some simple tags with a mixture of classes and IDs. Let’s update our script to this.

One of the methods in the selectors API is the document.querySelector() method. This method allows you to grab an element using a CSS query. In our case, we want to grab H1 elements. You pass in the CSS query using a string. From there, you can access any properties and methods for that element. Let’s take a look at another example.

Update your script to this.

Just like before, we use the querySelector() method to grab any elements with the CSS query .ex2. However, we have 2 div tags with the class ex2. The querySelector() will only grab the first instance it finds. If you refresh your document, then you will only see the first div with the class ex2 change. The querySelectorAll() method will grab all matches it finds.

Update your script to this.

When you use the querySelectorAll() method you’re returned an array of all matches found. We use a for loop to loop through all matches found and change the HTML inside.

You can also have complex CSS queries like so.

This will grab all <p> tags with the class ex3.


JQuery, a popular JavaScript library, uses the selectors API to grab DOM elements. Using the selectors API is preferred as it’s easier to use than the getDocumentById() method. For more information on the selectors API, then go here.


About Jasko Koyn

Check Also


Audio – Advanced JavaScript Tutorial

The video and audio objects both have the same events, properties and methods. So, you …

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.