Alejandro Garrido Alejandro Garrido - 7 months ago 12
Javascript Question

Replace content by class with JavaScript

How can I modify the content with Javascript selecting the elements by class?

Actually I tried using this:

document.getElementsByClassName("myClass").innerHTML = "new content"


But does nothing.
If I select the element by ID it's work

document.getElementById("myID").innerHTML = "new content"


But I need can select by class.

I only need to change the content inside a tag. Replacing a text to an img element for a woocommerce buttons.

Thanks!

Answer

getElementsByClassName will return array. So loop that array and do your logic:

var myClasses = document.getElementsByClassName("myClass");

for (var i = 0; i < myClasses.length; i++) {
  myClasses[i].innerHTML = "new content";
  }
<div class="myClass">old content</div>
<div class="myClass">old content</div>