qadenza
qadenza

Reputation: 9293

how to search a div's children for a string

<div id="store">
<img class="act" src="imgT/01.jpg" alt="img">
<img src="imgT/05.jpg" alt="img">
<img src="imgT/02.jpg" alt="img">
</div>

I need to search the #store's children and get the src attribute of the child which is consists of "05".

Something like:

var src = $("#store").children().find("05").attr("src");
alert (src);

I need imgT/05.jpg as result.

Upvotes: 0

Views: 34

Answers (4)

Ryan
Ryan

Reputation: 14649

$("#store").children().each(function() {
   var img = this.src.split('/').pop();
   if(img == '05.jpg') { 
      alert(this.src);
   }
});

http://jsfiddle.net/v28cdyvo/1/

Going further If the image extensions can't be determined we can just set up a regex to extract everything but numbers. Granted, that your images are stored will the file names as integers with 0's preprended to them. To do that you could this:

img = img.replace(/[^0-9]/g, '');

http://jsfiddle.net/v28cdyvo/

In consideration of the jQuery's each() method, you can't break out of the loop once you have found your match. You might think you can do a break statement, but that is illegal. If you have a lot of images, then this could affect performance. You can instead just use a basic for loop to traverse the array of objects and then break once you find it.

My code performs the fastest according to this bechmark

Upvotes: 1

j08691
j08691

Reputation: 207861

var src = $('#store img').filter(function () {
    return $(this).attr('src').match('05')
}).attr('src')
console.log(src);

Note that this will match 05 anywhere in the image src attribute.

Upvotes: 1

levi
levi

Reputation: 22697

You can try this.

var img_list = $("#store").children()

    $.each(img_list,function(index,value){

          var src = $(value).attr("src");
          var _src = src.split(".")[0];
              _src = src.split("/");
          if (_src == "05"){
              alert(src)
          }

    })

Upvotes: 1

Wondercricket
Wondercricket

Reputation: 7872

You can use a jquery wild card:

<div id="store">
    <img class="act" src="imgT/01.jpg" alt="img">
    <img src="imgT/05.jpg" alt="img">
    <img src="imgT/02.jpg" alt="img">
</div>

<script type="text/javascript">
    $(document).ready(function () {
        var src = $("#store").find("img[src*='05']").attr("src");
        alert(src);
    });
</script>

Upvotes: 3

Related Questions