Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I select a box which has specific text?

I have this HTML:

<h5>something</h5>
<ul>
   <li class="name">John</li>
   <li class="age">21</li>
</ul>
<h5>specific text</h5>
<ul>
   <li class="name">Peter</li>
   <li class="age">19</li>
</ul>
<h5>something else</h5>
<ul>
   <li class="name">Ali</li>
   <li class="age">62</li>
</ul>

I want to select this part:

<h5>specific text</h5>
<ul>
   <li class="name">Peter</li>
   <li class="age">19</li>
</ul>

The logic is the content of <h5> tag. I want the one which is specific text. Actually expected result is an array of both that name and that age. Some thing like this: var res = ['Peter', 19];.

But my code selects all those <ul>s:

$('ul').map(function (){
   var res = [$(this).find('li.name').text(), $(this).find('li.age').text()];
});

How can I fix it?

like image 570
Martin AJ Avatar asked Feb 05 '23 11:02

Martin AJ


1 Answers

You can use :contains() to find the H5 that contains the specific string you want. Then use .next() to get that ul associated with the h5

$("h5:contains('specific text')").next('ul').map(function (){
   var res = [$(this).find('li.name').text(), $(this).find('li.age').text()];
   console.log(res)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h5>something</h5>
<ul>
   <li class="name">John</li>
   <li class="age">21</li>
</ul>
<h5>specific text</h5>
<ul>
   <li class="name">Peter</li>
   <li class="age">19</li>
</ul>
<h5>something else</h5>
<ul>
   <li class="name">Ali</li>
   <li class="age">62</li>
</ul>
like image 161
Carsten Løvbo Andersen Avatar answered Feb 07 '23 11:02

Carsten Løvbo Andersen