Javascript add text to div by classname not adding and no errors either - Stack Overflow

I have a div with a class name:<div class="myclass"><div>And now I want to add s

I have a div with a class name:

<div class="myclass"></div>

And now I want to add some text to it, so I used this:

document.getElementsByClassName("myclass").innerHTML = 'Testing here';

For some reason no text is added and also console is not giving me any errors either.

What I'm I doing wrong here?

I have a div with a class name:

<div class="myclass"></div>

And now I want to add some text to it, so I used this:

document.getElementsByClassName("myclass").innerHTML = 'Testing here';

For some reason no text is added and also console is not giving me any errors either.

What I'm I doing wrong here?

Share Improve this question asked Oct 11, 2018 at 11:45 user10450072user10450072
Add a ment  | 

3 Answers 3

Reset to default 3

Document.getElementsByClassName()

Returns an array-like object of all child elements which have all of the given class names. When called on the document object, the plete 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.

Since getElementsByClassName returns array-like object, you have to use index.

I will also suggest you to use textContent instead of innerHTML when dealing with text only content.

document.getElementsByClassName("myclass")[0].textContent = 'Testing here';
<div class="myclass"></div>

document.getElementsByClassName("myclass") will return collection. So either you need to loop through each element or just use indexing if there is only one element

document.getElementsByClassName("myclass")[0].innerHTML = 'Testing here';

    var elements = document.getElementsByClassName("myclass");
    for(var i=0;i<elements.length;i++)
    {
      elements[i].innerHTML = 'Testing here';
    }
<div class="myclass"></div>

You can use document.querySelector also. Here's an example usage

    <div class="myclass"></div>
    document.querySelector(".myclass").textContent = 'Testing here';

Using querySelector returns a single element with specified css selector

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745512436a4630830.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信