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!
getElementsByClassName
will return array. So loop that array and do your logic:As others pointed out getElementsByClass returns an array.
If you are willing to use jquery it could simplify as
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.
document.getElementsByClassName
returns an array, as classes are not unique, whereasdocument.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.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 bydocument.getElementsByClassName("myClass")[0]
or assign some id to that particular element.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:
Classes are returned in an array, so you need to iterate the array.
Use something like this: