Andy Holmes Andy Holmes - 6 months ago 10
Javascript Question

Best way to replace/remove text from a string inside an li tag

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 &amp; 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?

Answer

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','');
    });
});
Comments