Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Catching an element by class name and adding innerHTML to it

I have had trouble getting hold of my elements class name. Now that I finally managed to do so, I do not seem to be able to add innerHTML to it.

I am adding an quote within an existing element. This is how I managed to get the class name as no other way of getElementsByClassName did not work:

var elements = document.getElementsByClassName('name-of-element');
for(var i=0; i<elements.length; i++) { 

}

I tried combining the two scripts I have like so:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var elements = document.getElementsByClassName('name-of-element');
for(var i=0; i<elements.length; i++) { 
  elements.innerHTML = 'the change I am trying to make';

}

I tried changing the "elements" of "elements.innerHTML" but have not figured out anything that would work.

Any help is greatly appreciated!

>Solution :

You need to use elements[i] in your loop, it’s not working because you’re trying to change the innerhtml of the html collection rather than of the individual elements inside it.

Remember that getElementsByClassName (plural elements) returns an array-like object called a html collection.

var elements = document.getElementsByClassName('name-of-element');

for(var i=0; i<elements.length; i++) {
  elements[i].innerHTML = 'the change I am trying to make';
}
<div class='name-of-element'></div>
<div class='name-of-element'></div>
<div class='name-of-element'></div>
<div class='name-of-element'></div>
<div class='name-of-element'></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading