Replace content by class with JavaScript

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

Actually I tried using this:

Read More
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!

Related posts

8 comments

  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";
      }
    <div class="myClass">old content</div>
    <div class="myClass">old content</div>
  2. As others pointed out getElementsByClass returns an array.
    If you are willing to use jquery it could simplify as

    $(".myClass").html("new content")
    
  3. 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";
    }
    
  4. 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.

  5. 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.

  6. ECMAScript 2015 (ES6) also provides the spread operator, which can be used to transform the HTMLCollection returned by getElementsBYClassName into a regular array and then combine it with forEach(), to change all array elements with the new content, with the line:

    [...document.getElementsByClassName('myClass')].forEach(element => {
        element.innerHTML = '<div>New Content</div>' }
    
  7. Use something like this:

    var elems = document.getElementsByClassName('myClass'), i;
    for (i in elems) {
        elems[i].innerHTML = "new content";
    }
    

Comments are closed.