Alex Marianetti
Alex Marianetti

Reputation: 39

change the text of every element in a class javascript

How do I change the text of all elements in a class If the element is in a division do I need to do anything else?

P.S. I hardly know js so plz help. enter image description here

Upvotes: 2

Views: 1626

Answers (2)

Abdelrahman Farag
Abdelrahman Farag

Reputation: 399

I hope these examples can help you

function myFunction()
{
x=document.getElementsByClassName("infoblock");  // Find the elements
    for(var i = 0; i < x.length; i++){
    x[i].innerText="text changed!";    // Change the content
    }

}
function myFunction2()
{
x=document.getElementsByClassName("notationgrade");  // Find the first span elements
y=document.getElementsByClassName("percentgrade");  // Find the second span elements
    for(var i = 0; i < x.length; i++){
    x[i].innerText="text 1 changed!";    // Change the content
    }
    for(var i = 0; i < y.length; i++){
    y[i].innerText="text 2 changed!";    // Change the content
    }
}
<body>

<div class="class-stats fsClassStatsAverage">
  <p><span class="infoblock notationgrade">old text 1 </span></p>
 <p> <span class="infoblock percentgrade">old text 2</span></p>
</div>    
<button type="button" onclick="myFunction()">Change All Spans</button>
<button type="button" onclick="myFunction2()">Change Each Span</button>
</body>

Upvotes: 1

You can use querySelectorAll and with a foreach set the new text:

const examples = document.querySelectorAll('.example');

examples.forEach(example => {
  example.innerHTML = 'new text';
});
<div class="example">
  text 1
</div>

<div class="example">
  text 2
</div>

Upvotes: 4

Related Questions