简体   繁体   English

如何在JavaScript中按类获取HTML元素?

[英]How can I get HTML elements by class in JavaScript?

I'm trying to manipulate the HTML through getElementsByClass() but for some reason it doesn't work. 我试图通过getElementsByClass()来操纵HTML,但由于某种原因它不起作用。 When I use document.getElementByID() it works? 当我使用document.getElementByID()它有效吗? Why is this? 为什么是这样?

<div class='boldStuff'> <p>Welcome to the site. </p> </div>

<script type="text/javascript">
    document.getElementsByClass('boldStuff').innerHTML = 'Fred Flinstone';
</script>

尝试:

document.getElementsByClassName('boldStuff')[0]

Here's a widely supported solution: 这是一个广泛支持的解决方案:

function getElementsByClassName( root, clss ) {

    var result = [], els, i;

    if( arguments.length < 2 || !root || !clss || root.nodeType !== 1 ) {
        return result;
    }

    clss = clss + '';

    if( root.getElementsByClassName ) {
        result = root.getElementsByClassName( clss );
    } else if( root.querySelectorAll ) {
        result = root.querySelectorAll( '.' + clss );
    } else {
        els = root.getElementsByTagName('*');
        clss = " " + clss + " ";
        for( i = 0; i < els.length; ++i ) {
            if( ( " " + els[ i ].className + " " ).indexOf( clss ) !== -1 ) {
                result.push( els[ i ] );
            }
        }
    }
    return result;
}

Then use it like this: 然后像这样使用它:

var bold = getElementsByClassName( document, "boldStuff" );

for( var i = 0; i < bold.length; ++i ) {
    bold[ i ].innerHTML = 'Fred Flinstone';
}

The benefit to this is that it uses the native methods wherever possible. 这样做的好处是它尽可能使用本机方法。

  • It first tries getElementsByClassName because it is generally fastest. 它首先尝试getElementsByClassName因为它通常最快。

  • Then it tries querySelectorAll , which will bring in support for IE8 . 然后它尝试querySelectorAll ,这将带来对IE8支持。

  • Finally, it does a manual filtering of all elements under the provided root. 最后,它对提供的根目录下的所有元素进行手动过滤。

getElementsByClassName returns a NodeList. getElementsByClassName返回NodeList。 you will have to use 你将不得不使用

document.getElementsByClassName('boldStuff')[0].innerHTML

refer the docs at mdn 参考mdn的文档

The correct method to call is getElementsByClassName() , and it will give you an array of elements. 调用的正确方法是getElementsByClassName() ,它将为您提供一个元素数组。

document.getElementsByClassName('boldStuff')

Anyway this is not compatible with older IE version. 无论如何,这与旧的IE版本不兼容。 Check the compatibility here . 检查兼容性这里

它返回一个数组,因此设置数组的innerHTML的第一个元素

document.getElementsByClassName('boldStuff')[0].innerHTML = 'Fred Flinstone';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM