Reputation: 2365
jsFiddle: http://jsfiddle.net/WM6wG/
I'm trying to replace a text in a div, but cannot seem to figure out why it's not working.
HTML:
<div class="text">abc</div>
<div class="text">foo</div>
<div class="text">bar</div>
jQuery:
var match = 'abc';
if ($('div.text:contains(match)')) {
$('div.text').html(function(){
$(this).replaceText(match, 'xyz');
}
}
Ideally the expected output should be: xyz foo bar
but it remains abc foo bar
, what am I doing wrong?
Upvotes: 1
Views: 4496
Reputation: 103368
There are a few issues with your code:
You are searching for "match" rather than the value of the variable match
.
Your if
statement is pointless as you have a fresh selector for div.text
on the next line. So if one of the elements matches, your code will run this against all matching elements anyway.
Your html()
method is not returning anything.
replaceText()
is not a standard function. Unless this is a custom function you have made, or you are using the replaceText() plugin, replace it with replace()
var match = 'abc';
$("div.text:contains(" + match + ")").each(function(){
var $this = $(this);
$this.html(function(){
return $this.html().replace(match, "xyz");
});
});
Live Demo: http://jsfiddle.net/wh7xn/
If there are multiple instance of "abc" you wish to replace, use RegEx:
var match = 'abc';
var re = new RegExp(match,"g");
$("div.text:contains(" + match + ")").each(function(){
var $this = $(this);
$this.html(function(){
return $this.html().replace(re, "xyz");
});
});
Live Demo: http://jsfiddle.net/wh7xn/2/
Upvotes: 7
Reputation: 207901
This seems to do it all in one line (not counting your var declaration):
var match = 'abc';
$('div.text:contains(' + match + ')').text($('div.text:contains(' + match + ')').text().replace(match, 'xyz'));
No if statement needed and replace
instead of replaceText
.
If you'll have multiple matches, use this:
var match = 'abc';
$('div.text:contains(' + match + ')').each(function () {
$(this).text($(this).text().replace(match, 'xyz'));
});
Upvotes: 1
Reputation: 8420
See the updated fiddle
$(document).ready(function(){
var match = 'abc';
if ($('div.text:contains('+match+')')) {
$('div.text').html(function(){
$(this).replaceText(match, 'xyz');
});
}
});
2 things!
'('+match+')'
Upvotes: 1
Reputation: 141827
When you do $('div.text:contains(match)')
you are searching for a div containing the literal string 'match'.
You could do it like this: $('div.text:contains(' + match + ')')
Just be careful that the variable match doesn't containing anything of significance to the jquery selector such as a )
.
Upvotes: 2