Kazen
Kazen

Reputation: 110

Replace innerHTML of divs with same class based on content

I am trying to only replace the content of the div with the "replace this".

The content of each div is dynamically created, so i have to check which class needs to be changed. I tried it with a for-loop and so far I am getting the right div but having trouble changing its content. The main problem is that they all have the same class. How can I put the new text into the correct div without changing the others?

var x = document.getElementsByClassName("class_name");
var teststring = "rep";

for (i = 0; i < x.length; i++) {
  if (x[i].toString().indexOf(teststring) > 0) {
    this.innerHTML = "text3";
  }
}
<div class="class_name">
  text1
</div>
<div class="class_name">
  text2
</div>
<div class="class_name">
  replace this
</div>

Upvotes: 0

Views: 250

Answers (2)

Mamun
Mamun

Reputation: 68943

Declare the variable with let in the for loop which will create it's own scope within curly braces ({...}). Instead of using this, use the current element with x[i]. x[i] refers to the element itself, you have to take the content from it.

I will prefer textcontent instead of innerHTML

var x = document.getElementsByClassName("class_name");
var teststring = "rep";

for (let i = 0; i < x.length; i++) {
  if (x[i].textContent.indexOf(teststring) > 0) {
    x[i].textContent = "text3";
  }
}
<div class="class_name">
  text1
</div>
<div class="class_name">
  text2
</div>
<div class="class_name">
  replace this
</div>

Upvotes: 4

Leo
Leo

Reputation: 680

Use x[i].innerHTML not this.innerHTML

var x = document.getElementsByClassName("class_name");
var teststring = "rep";

for (i = 0; i < x.length; i++) {
    if(x[i].innerHTML.indexOf(teststring) !== -1) {
    x[i].innerHTML = "text3";
}
}

DEMO https://jsfiddle.net/0cmz4pvk/5/

Upvotes: 1

Related Questions