How to get element by class name

前端 未结 4 1185
余生分开走
余生分开走 2020-12-03 17:45

I want to know if there is a way to getElementByClassName(\"classname\").innerHTML function or something to the equivalent of getElementById(\"ClassName\"

4条回答
  •  被撕碎了的回忆
    2020-12-03 18:20

    You are missing an s in your function name. getElementsByTagName returns a collection of elements, of elements, which you need to iterate over:

    var elements = document.getElementsByClassName("classname");
    
    for (var i = 0; i < elements.length; i++) {
        elements[i].innerHTML = 'foo';
    }
    

    IE8 and below don't support getElementsByClassName, so you'll have to find a polyfill or use querySelectorAll (IE8).

提交回复
热议问题