Change css class for all elements with the specified class using javascript

Basically I try to find all elements with a specific class name and switch it to another. I have another function that switches this back to the original class name. Here is my function called with onclick:

function showEventsAppliedTo() { var myObj = document.getElementsByClassName('notApplied'); while (myObj.length >= 0) { myObj[0].className = 'mblListItem notAppliedOut'; } AppliedToButton.set('style', 'display:none;'); EventListingButton.set('style', 'display:block;'); } 

I get an error: myObj [0] - undefined. Any idea why this is happening?

As a note, we use Dojo, therefore, the last line of the function. I know that I could easily do this with jQuery, but we don’t use it, and it makes no sense to load another framework.

Thanks in advance for your help.

EDIT

Thanks to the help of Abhishek Mishra, I changed how I handle this loop and found a way to do it with JUST Dojo, which I preferred. Here is the code:

 function listingClassToggle() { dojo.query(".notApplied").addClass("notAppliedOut"); dojo.query(".notApplied").removeClass("notApplied"); } 

Simpler code and much easier than my previous solution. Thanks for your help. Hope this helps someone else.

+6
source share
1 answer

You just need to check > 0 not >= 0 . When the length is zero, there is no null element.

+5
source

Source: https://habr.com/ru/post/927274/


All Articles