1

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?

user229044
  • 232,980
  • 40
  • 330
  • 338
Andy Holmes
  • 7,817
  • 10
  • 50
  • 83

2 Answers2

4

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','');
    });
});
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • But you are completly destroying HTML markup this way. Selector should be in this case: `'li > a:contains("Parent")'` – A. Wolff Apr 18 '16 at 12:43
  • @A.Wolff - that's true, the entire markup in the LI would be replaced by the text, edited it. – adeneo Apr 18 '16 at 12:46
0

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, ''));
});
DunningKrugerEffect
  • 603
  • 1
  • 5
  • 18