How can I get HTML elements by class in JavaScript?

后端 未结 5 1411
渐次进展
渐次进展 2021-01-22 03:15

I\'m trying to manipulate the HTML through getElementsByClass() but for some reason it doesn\'t work. When I use document.getElementByID() it works? Wh

相关标签:
5条回答
  • 2021-01-22 03:30

    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.

    • Then it tries querySelectorAll, which will bring in support for IE8.

    • Finally, it does a manual filtering of all elements under the provided root.

    0 讨论(0)
  • 2021-01-22 03:31

    The correct method to call is getElementsByClassName(), and it will give you an array of elements.

    document.getElementsByClassName('boldStuff')
    

    Anyway this is not compatible with older IE version. Check the compatibility here.

    0 讨论(0)
  • 2021-01-22 03:43

    It returns an array so set the first element of the array's innerHTML

    document.getElementsByClassName('boldStuff')[0].innerHTML = 'Fred Flinstone';
    
    0 讨论(0)
  • 2021-01-22 03:44

    Try:

    document.getElementsByClassName('boldStuff')[0]
    
    0 讨论(0)
  • 2021-01-22 03:45

    getElementsByClassName returns a NodeList. you will have to use

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

    refer the docs at mdn

    0 讨论(0)
提交回复
热议问题