How to get element by class name

前端 未结 4 1167
余生分开走
余生分开走 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:07

    I suggest you to use JQuery, where you can use directly CSS selectors (like .yourclass) to find all elements of a given class:

    $('.yourclass').doWhatYouWant();
    

    If you prefer not to use JQuery, you can use plain Javascript:

    document.getElementsByClassName('my-fancy-class')
    

    But be careful with IE8 incompatibility issue. As an alternative (slower but you can build more complex CSS selectors) you can use:

    document.querySelector('.cssSelector')
    

    Which will return one element responding to your CSS selector, or

    document.querySelectorAll('.cssSelector')
    

    Which will return multiple elements instead.

    0 讨论(0)
  • 2020-12-03 18:12

    You can do this using jquery

    $('.className').html();
    

    http://api.jquery.com/html/

    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2020-12-03 18:33

    If tou use jQuery you can get it as you would in a CSS selector so:

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
    

    then...

    $('.classname').each(function() {
        // get html
        $(this).html();
        // set html
        $(this).html('something');
    });
    

    Notice you have also convenient way to manage innerHTML.

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