Reputation: 8077
I'm working on a sitemap list in ExpressionEngine (so I don't have too much flexibility on how things are rendered) and I need to remove the word 'Parent' from a string if it exists.
Below is an example of HTML output:
<li class="sitemap-item">
<a href="">About Us Parent</a>
<ul>
<li class="sitemap-item">
<a href="">About Us</a>
<ul>
<li class="sitemap-item">
<a href="http://website.dev/about-us/meet-the-directors">Meet the Directors</a>
</li>
<li class="sitemap-item">
<a href="">Partners</a>
</li>
<li class="sitemap-item">
<a href="">Accreditation & Awards</a>
</li>
<li class="sitemap-item">
<a href="">Testimonials</a>
</li>
<li class="sitemap-item">
<a href="http://website.dev/careers">Careers</a>
</li>
</ul>
</li>
</ul>
</li>
I tried the following jQuery with no luck, just doesn't replace the word at all:
$(document).ready(function(){
if($('li:contains("Parent")')){
$(this).replace('Parent','');
};
});
As you can see I'm trying to do this with jQuery. Can anyone shed some light on the correct way to do this?
Upvotes: 1
Views: 1013
Reputation: 318312
jQuery doesn't have a replace
method, it's a native method for strings, meaning you have to get the text first as a string, for instance with text()
, and then return the changed string back again
$(document).ready(function(){
$('li > a:contains("Parent")').text(function(_, txt) {
return txt.replace('Parent','');
});
});
Upvotes: 4
Reputation: 613
You can use the replace()
method with a regex to make sure you replace all instances of the word. replace()
with strings only replaces the first occurance.
$(document).ready(function(){
var elements = $('li');
elements.html(elements.html().replace(/Parent/gi, ''));
});
Upvotes: 0