Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 232
Alejandro Garrido Avatar asked Dec 04 '22 00:12

Alejandro Garrido


2 Answers

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>
like image 172
Justinas Avatar answered Jan 27 '23 13:01

Justinas


As others pointed out getElementsByClass returns an array. If you are willing to use jquery it could simplify as

$(".myClass").html("new content")
like image 27
Ein2012 Avatar answered Jan 27 '23 12:01

Ein2012