Alejandro Garrido Alejandro Garrido - 2 years ago 90
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>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download