Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addClass to getElementsByClassName array

I need a little help as i am getting frustrated with .getElementsByClassName. I have an svg map that has paths with classes. I now need to list all with a certain class and add another class. Right now i have

var testarray = (document).getElementsByClassName("currentclass");
for(var i = 0; i < testarray.length; i++)
{
   testarray.item(i).className("classtobeadded");
}

This returns me a "undefined is not a function" error. I've tried $(document), (document), (jQuery), i've tried $(".currentclass").addClass(), i've tried lots of combinations without success. Can you guys tell what i am doing wrong?

Thank you!

like image 839
Mind_meddler Avatar asked Jul 22 '14 21:07

Mind_meddler


2 Answers

You have a couple syntax errors, this should get it done:

var testarray = document.getElementsByClassName("currentclass");
for(var i = 0; i < testarray.length; i++)
{
    testarray[i].className += "classtobeadded";
}

Or since you're using jQuery you can do:

$(".currentclass").each(function() {
    $(this).addClass("classtobeadded");
});
like image 147
tymeJV Avatar answered Oct 09 '22 22:10

tymeJV


This jQuery should also work

  $(".currentclass").addClass("classtobeadded");
like image 27
kgf3JfUtW Avatar answered Oct 09 '22 23:10

kgf3JfUtW