Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change css class for all elements with said class with Javascript

Basically I'm trying to find all the elements with a particular class name and switch it to another. I have another function that switches this back to the original class name. Here's my function that's triggered with an 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'm getting an error saying myObj[0] is undefined. Any idea why this is happening?

As a note, we're using Dojo, hence the last line of the function. I know I could easily do this with jQuery, but we're not using it and it doesn't make sense to load another framework.

Thanks in advance for your help.

EDIT

Thanks to the help from Abhishek Mishra, I modified how I'm handling this loop and found a way to do it with JUST dojo, which is what I preferred. Here's the code:

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

Much simpler code and a lot lighter than my previous solution. Thanks for all your help. I hope this helps someone else.

like image 263
chazthetic Avatar asked Oct 09 '12 16:10

chazthetic


1 Answers

Should just test for > 0 not >= 0. When the length is equal to zero, there's no element zero.

like image 110
Pointy Avatar answered Sep 30 '22 07:09

Pointy