Alejandro Garrido Alejandro Garrido - 1 year ago 58
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.


Answer Source

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>