KillM
KillM

Reputation: 17

How to replace multiple occurrences of innerHTML of a div using javascript?

For a div that appears multiple times in your HTML :

<div class="myclass">abc</div>
<div class="myclass">abc def</div>
...

How can I achieve the replacement of "abc" for all the occurrences ? (I found resources to replace the first occurrence but not the rest)

This is my code with javascript method

<script>
 function addLoadEvent(func) {
   var oldonload = window.onload;
   if (typeof window.onload != 'function') {
     window.onload = func;
   } else {
     window.onload = function() {
       if (oldonload) {
         oldonload();
       }
       func();
     }
   }
 } 

 addLoadEvent(function() {  

    oldText = document.getElementsByClassName("myclass").innerHTML; 
    for (i = 0; i<oldText.length; i++){ 
    newText = oldText[i].innerHTML;
    newText = newText.replace(/abc/g, "123");
    oldText[i].innerHTML = newText;

    });
</script>

Upvotes: 0

Views: 1328

Answers (2)

Abhay Maurya
Abhay Maurya

Reputation: 12277

target every class, split value, remove 0 index and concatenate.

  $('.myclass').each(function(){
       var data = $(this).val();
       var data_array = data.split();
       var new = '';
       for(var i=1; i<data_array.length; i++){
          var _new += ' '+data_array[i];
       }
       $(this).val(_new);
    });

Upvotes: 0

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48367

Here is solution:

The problem is at this line: oldText = document.getElementsByClassName("myclass").innerHTML;

.innerHTML method returns HTML content.

You only need to get elements by class name, and obtain a nodeList.

oldText = document.getElementsByClassName("myclass");

function addLoadEvent(func) {
   var oldonload = window.onload;
   if (typeof window.onload != 'function') {
     window.onload = func;
   } else {
     window.onload = function() {
       if (oldonload) {
         oldonload();
       }
       func();
     }
   }
 }
 addLoadEvent(function() {  
    oldText = document.getElementsByClassName("myclass"); 
    for (i = 0; i<oldText.length; i++){ 
      newText = oldText[i].innerHTML;
      newText = newText.replace(/abc/g, "123");
      oldText[i].innerHTML = newText;
    }
 });
<div class="myclass">abc</div>
<div class="myclass">abc def</div>

Upvotes: 3

Related Questions