1

Possible Duplicate:
jQuery find and replace string

This is my html:

<div class="dt_lft">There is an error</div>

I need to find whether the div has the text error and replace that text with success using class name. How to do this?

Community
  • 1
  • 1
Sam Hanson
  • 1,317
  • 4
  • 22
  • 48

4 Answers4

8

You can use the :contains() selector:

$("div.dt_lft:contains('error')").text(function(i, text) {
    return text.replace('error', 'success');
});

If it's likely that the string error will occur more than once in the text, you'll need to use a RegEx to handle that:

$("div.dt_lft:contains('error')").text(function(i, text) {
    return text.replace(new RegExp('error', 'g'), 'success');
});
BenM
  • 52,573
  • 26
  • 113
  • 168
2
$("div.dt_lft:contains('error')").text(function(i,text){
   return text.replace('error', 'success');
});

http://jsfiddle.net/ztCcB/1/


$("div.dt_lft:contains('error')") returns all divs with class dt_lft containing word error, you can read more about jQuery contains selector. With jQuery .text() you can write function like:

$(object).text(function(index,CurrentContent){
   //somecode here
}

Elsewhere, if your object contains word error many times, you can do:

text.split('error').join('success');

In case you do not want to use RegEx.

loler
  • 2,594
  • 1
  • 20
  • 30
  • 1
    I love the fact that this gets accepted, despite being pretty much identical to mine... Oh, I love SO! – BenM Jan 09 '13 at 12:24
  • @BenM it's me, upvoter of your comment :D – loler Jan 09 '13 at 12:25
  • @loler - there is no justice in this world... :-P – BenM Jan 09 '13 at 12:26
  • Just for reference, using `.split('string').join('string')` is a **lot** slower than using RegExp! – BenM Jan 09 '13 at 12:29
  • 1
    @BenM you know, i just try to avoid regular expressions, coz people asking such question usually are not fluent in it. But of course it must be mentioned. – loler Jan 09 '13 at 12:30
0

Try this

var m=$(".dt_lft").html();
m=m.replace("error","success");
$(".dt_lft").html(m);
Rohit Patel
  • 459
  • 2
  • 14
0

Try this,

if($("div.dt_lft:contains('error')")){
  $('.dt_lft').replace('error','success');
}
Swarne27
  • 5,521
  • 7
  • 26
  • 41