Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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";
  }
<divclass="myClass">old content</div><divclass="myClass">old content</div>

Solution 2:

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

$(".myClass").html("new content")

Solution 3:

document.getElementsByClassName returns an array, as classes are not unique, whereas document.getElementById returns just an object (it should be unique).

Long story short, try document.getElementsByClassName("myClass")[i].innerHTML = "new content" where i can take values from 0 to n-1, where n is the number of elements with the .myclass class.

Solution 4:

Your class name is not unique. i.e The same class name is used by many other elements. So document.getElementsByClassName("myClass") this will retrun an array containing all the classes. So, either you need to select the porper class by document.getElementsByClassName("myClass")[0] or assign some id to that particular element.

Solution 5:

getElementsByClassName returns an array so you have to loop that array to change the content having your given class. You can try following to code. I hope it will help you.

var arr = document.getElementsByClassName("myClass");
for (var i = 0; i < arr.length; i++) {
   arr[i].innerHTML = "new content";
}

Post a Comment for "Replace Content By Class With Javascript"