magento two magento two - 5 months ago 6
jQuery Question

Replace a text using JQuery

Hi I am trying to replace a text using JQuery. but it's replacing with duplicate text.

I have tried below code:

HTML Code

<a class="text_div">
This div contains some text.
</a>
<br>
<a class="text_div">
This div contains some text.
</a>
<br>
<a class="text_div">
This div contains some text.
</a>


jQuery Code

$(document).ready(function(){
var text = $('[class="text_div"]').text();
var new_text = text.replace("contains", "hello everyone");
$('[class="text_div"]').text(new_text);
});


Resulted OUT Put

This div hello everyone some text. This div contains some text. This div contains some text.
This div hello everyone some text. This div contains some text. This div contains some text.
This div hello everyone some text. This div contains some text. This div contains some text.


Expecting Out Put

This div hello everyone some text.
This div hello everyone some text.
This div hello everyone some text.

Answer

Try like this

  $('.text_div').each(function(x){
    var new_text = $(this).text().replace("contains", "hello everyone"); 
    $(this).text(new_text);
  })

for the question in the comment try:

<a class="text_div">
    This div contains - some text.
</a>
  $('.text_div').each(function(x){
        var new_text = $(this).text().split('-'); 
        $(this).html(new_text[0]+'span style="color:red;font:bold;">'+new_text[1]+'</span>');
      })