0

I have few divs with a single class name, my objective is to change the class name value of the div when a particular link is clicked, and below was my approach.

I stored class name values in an array, then used document.getElementsByClassName("test") and stored it into an array elements, and then I ran a for loop to replace class name value. :

function changeClass(value){
    style = [ 'view view-first', 'view view-second', 'view     view-third', 'view view-fourth', 'view view-fifth' ];
    var elements = document.getElementsByClassName("test");
    for(var i = elements.length - 1; i >= 0; i++)
    {
        elements[i].className = style[value];
    }   
}

When I run this code, only a single div class name is replaced. I want all the class name to be replaced.

2
  • i-- or for(var i=0; i<elements.length;i++) Commented Nov 5, 2015 at 13:05
  • that was a grave error, thanks mate for the help. Commented Nov 5, 2015 at 13:07

3 Answers 3

2

Try this:

function changeClass(value){
    style = [ 'view view-first', 'view view-second', 'view     view-third', 'view view-fourth', 'view view-fifth' ];
    var elements = document.getElementsByClassName("test");
    for(var i = elements.length - 1; i >= 0; i--)
    {
        elements[i].className = style[value];
    }   
}

OR

function changeClass(value){
    style = [ 'view view-first', 'view view-second', 'view     view-third', 'view view-fourth', 'view view-fifth' ];
    var elements = document.getElementsByClassName("test");
    for(var i=0; i<elements.length;i++)
    {
        elements[i].className = style[value];
    }   
}
Sign up to request clarification or add additional context in comments.

Comments

0
var elems = $('.oldclasses');
elems.removeClass('oldclasses');
elems.addClass('newClass');

So you not need $.each function for that jquery can apply the commands to all elems or single elem.

Comments

0

Try:

style = [ 'view view-first', 'view view-second', 'view     view-third', 'view view-fourth', 'view view-fifth' ];
$('.test').each(function(i,v) {
     if (style[i]) {
        $(this).attr('class',style[i]);
     }
});

1 Comment

you have the jquery tag

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.