innerHTML isn't working with getElementsByClassName

后端 未结 2 394
傲寒
傲寒 2020-12-20 05:43

I\'m just a beginner. And I\'m trying to use innerHTML. I think I wrote proper code, but it doesn\'t work. When I click the trigger, the page becomes white and

2条回答
  •  时光说笑
    2020-12-20 06:23

    getElementsByClassName() returns array with elements.

    Returns an array-like object of all child elements which have all of the given class names. When called on the document object, the complete document is searched, including the root node. You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class names.

    So you need iterate array and set innerHTML like this i.e.

    var elements = document.getElementsByClassName('myClass');
    Array.prototype.forEach.call(elements, function(element) {
        element.innerHTML = 'Your text goes here';
    });
    

    Also a little bonus JSFiddle

提交回复
热议问题