最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Equivalent of getElementById for Classes in Javascript - Stack Overflow

programmeradmin4浏览0评论

I'm currently making a game, and I'm trying to change the CSS values of a whole class of objects. For a single ID, I would use, document.getElementById("idHere"), but I need something like document.getElementByClass("classHere"). Thanks!

I'm currently making a game, and I'm trying to change the CSS values of a whole class of objects. For a single ID, I would use, document.getElementById("idHere"), but I need something like document.getElementByClass("classHere"). Thanks!

Share Improve this question asked Jan 25, 2014 at 1:42 Jonathan SpiritJonathan Spirit 5993 gold badges7 silver badges14 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 6

There is simply document.getElementsByClassName("myClass"), which returns an array of all the elements with that HTML class.

If you're using jQuery, you can do it with $(".myClass"), which will return a collection of all of the elements with that class.

There exists getElementsByClassName; see document.getElementsByClassName on MDN.

If you can use JQuery I suggest $('.classHere').

Two ways to do it:

document.getElementsByClassName("theClassName");
document.querySelectorAll(".theClassName");

These methods won't work on older browsers (like IE7 or IE8). In this case you'll have to iterate through elements to check the class name, or rely on a library like jQuery.

If you can't or don't want to use jQuery, do the following:


function changeClassName(className, newClassName) {

    var elements = document.getElementsByClassName(className);

    for (var i = 0; i < elements; ++i) {
        var item = elements[i];  
        item.className = newClassName;
    }

}


If you decide to use jQuery:

function changeClassName(className, newClassName) {

    $('.'+className).toggleClass(newClassName);

}

If you need to change CSS values according to class name you can just use:

document.getElementsByClassName("classname");

this will return you an array of all elements in whole document that have class which you search.

This will allow you to write a loop to change CSS for all of returned elements.

发布评论

评论列表(0)

  1. 暂无评论