Iterate over <li> and replace text with jquery

265 Views Asked by At

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?

2

There are 2 best solutions below

1
On BEST ANSWER

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>

1
On

Just use replace on the HTML of the parent div and then reset the HTML using the replaced content:

$(".mydiv" ).html($(".mydiv" ).html().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>