2

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?

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
  • 2
    Please show us your work (your code), and at which point exactly you got stuck. We are not a free coding facility ... ;-) – Andreas Gnyp Aug 19 '16 at 11:42
  • As I wanted to adapt my jquery code, the answers were already there and they worked very well for my problem. It wasn't ment to replace my work or code for me, but sometimes people are quite new with some programming languages and may also not even have an idea what to use for specific problems ;) – middleendian Aug 19 '16 at 13:40

2 Answers2

0

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>
Kld
  • 6,970
  • 3
  • 37
  • 50
  • You can use `.text(function)`, here is sample code `$('.mydiv > ul > li:contains("4")').text(function(_, val) { return val.replace(/4/, "four") });` – Satpal Aug 19 '16 at 11:45
0

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>
gavgrif
  • 15,194
  • 2
  • 25
  • 27
  • Thank you for this solution aswell. All of the answers worked just fine for me though my real code was a bit complicated and I had to adapt each solution to try how and if it works :) Thank you for your effort. It just saved me some hours! – middleendian Aug 19 '16 at 13:35