SamsungBrown
SamsungBrown

Reputation: 21

Adding a class using JavaScript

Could anyone give me a hand with the following JavaScript issue.

I am trying to come up with a function that adds a class to a div that has a specified class.

I have tried to come up with something based on what a few people have said but it doesn't seem to work.

http://jsfiddle.net/samsungbrown/vZ9Hu/

Where am I going wrong?

Thanks

function toggleClass(matchClass,content) {
    var elems = document.getElementsByTagName('*'),i;
    for (i in elems) {
        if((" "+elems[i].className+" ").indexOf(" "+matchClass+" ") > -1) {
            elems[i].classList.toggle(content);
        }
    }
}

window.onload = function () {
    toggleClass("col-left","display");
}

Upvotes: 2

Views: 55

Answers (1)

Halcyon
Halcyon

Reputation: 57729

Because of some quirks in jsFiddle your code doesn't run. Remove the .onload wrapper and your code runs. See: http://jsfiddle.net/vZ9Hu/1/

Upvotes: 1

Related Questions