Friday , 17 November 2017
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.

Conclusion

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.

http://www.w3.org/TR/selectors-api/

About Jasko Koyn

Check Also

Try-Catch Statement

Try-catch Statement – Advanced JavaScript Tutorial

The try-catch statement is a unique way to handle errors. When errors occur, usually it …

Leave a Reply

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

ULTIMATE WORDPRESS DEVELOPMENT COURSE
Want to learn how to create your own custom WordPress plugins and themes? Check out my course!
Get 93% off my course. You'll also learn how to integrate WooCommerce and BuddyPress into your projects. This is a limited time offer
Yes, I would like to get 93% off your course!
No Thanks!
close-link