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 user10450072user104500723 Answers
Reset to default 3Document.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条)