Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 448
Bojjaiah Avatar asked Mar 19 '26 16:03

Bojjaiah


1 Answers

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>');
      })
like image 53
Anik Islam Abhi Avatar answered Mar 22 '26 04:03

Anik Islam Abhi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!