Search code examples
jqueryhtmlreplaceiterated-function

Iterate over <li> and replace text with jquery


I have the following HTML structure:

<div class="mydiv">
  <ul>
    <li>Text 1</li>
    <li>Text 2</li>
  </ul>
  <ul>
    <li>Text 3</li>
    <li>Text 4</li>
  </ul>
  <ul>
    <li>Text 5</li>
  </ul>
</div>

I want to find a string containing "4" and replace it with "four". Other strings from other li elements of this div are then no longer interesting for me. How can I do this if I only know in which div I should search but not which li element?


Solution

  • You can use the :contains selector

    $( "div li:contains('4')" ).text(function(_, val) { 
        return val.replace(/4/, "four")
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="mydiv">
      <ul>
        <li>Text 1</li>
        <li>Text 2</li>
      </ul>
      <ul>
        <li>Text 3</li>
        <li>Text 4</li>
      </ul>
      <ul>
        <li>Text 5</li>
      </ul>
    </div>