user6920839 user6920839 - 2 months ago 10
jQuery Question

How can we search in dom for a text with jquery

I have a

<div id='imgBody'>
and that has an image tag and it's src is
src="a1.jpg"
. I have another div and inside of it I have ul tag and many li's inside of it, and image tags inside of each li. One of those image tags also has
src="a1.jpg"
. I have src of main div in a variable and I want to search the image which has that src inside li's and I want to get the index of found image tag's parent li.

How can I achieve this?

HTML

<div id='imgBody'><img src="img/a1.jpg"></div>

<div id='main'>
<ul class="ulthumbs">
<li class="thumbImg" data-rel="a0">
<img src="img/a0.jpg" width='150' height="80">
</li>
<li class="thumbImg" data-rel="a1">
<img src="img/a1.jpg" width='150' height="80">
</li>
<li class="thumbImg" data-rel="a2">
<img src="img/a2.jpg" width='150' height="80">
</li>
</div>


JQUERY

var getImgTag = $('#imgBody').children().attr('src');
var findIndex = find(getImgTag).index();
console.log(findIndex);

Answer

Target the LI that contains an image with the same source

var getImgTag = $('#imgBody img').attr('src');
var findIndex = $('li:has(img[src="' + getImgTag + '"])').index();

console.log('The index is : ' + findIndex);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='imgBody'>
  <img src="img/a1.jpg">
</div>

<div id='main'>
  <ul class="ulthumbs">
    <li class="thumbImg" data-rel="a0">
      <img src="img/a0.jpg" width='150' height="80">
    </li>
    <li class="thumbImg" data-rel="a1">
      <img src="img/a1.jpg" width='150' height="80">
    </li>
    <li class="thumbImg" data-rel="a2">
      <img src="img/a2.jpg" width='150' height="80">
    </li>
  </ul>
</div>