addClass to getElementsByClassName array

不羁岁月 提交于 2019-12-12 15:07:12

问题


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!


回答1:


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");
});



回答2:


This jQuery should also work

  $(".currentclass").addClass("classtobeadded");



回答3:


You have some errors on your code

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

You have to pay attention, you have to add a little space to add a new class like this

testarray.item(i).className += " classtobeadded";


来源:https://stackoverflow.com/questions/24897781/addclass-to-getelementsbyclassname-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!