Simple Class Processing in JavaScript

Processing an id in JavaScript is easy since there can be only one. If we have a big chunk of code that needs to reference the element we can simply assign the element to a short variable name and then use that for all of the necessary references to it.

In the following code the console.log call is standing in for whatever series of statements you need to have reference the element with an id of 'myid'.

el = document.getElementById('myid');

Being able to do the same for all the elements having a specific class used to be far more complicated and the code to process each needed to be significantly different from the corresponding code to process an id.

The 2011 version of JavaScript resolved this with the introduction of the forEach method on arrays. It also introduced the querySelectorAll method for accessing elements in the page that means that this approach is not limited to just processing a class but in fact can be used for processing elements matching to any CSS selector you like.

Now what you get back from a getElementsByClassName or querySelectorAll is a nodelist or collection rather than an array but we can borrow the forEach method from Array and apply it to our nodelist or collection using the Function call method.

So the following code is the equivalent of the above code for an id except that instead of processing the element with an id of "myid" it processes all of the elements which have a class of "myclass". As with the above code the console.log call here again represents all of the code you need to have reference each element and you will note that the way to reference each element is exactly the same as the above.

[]'.myclass'), function(el) {


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow