Cataclysm
Cataclysm

Reputation: 8548

How to get first child with specify element in JQuery?

I have following HTML..

<div class = "thumbnail">
  <img src = "somePath">
</div>
 <div class = "thumbnail">
  <img src = "somePath">
</div>
<div class = "thumbnail">
  <img src = "somePath">
</div>
<div class = "thumbnail">
  <a href = "someLink"><img src = "somePath"></a>
</div>
<div class = "thumbnail">
  <a href = "someLink"><img src = "somePath"></a>
</div>

I want to iterate img tags under the first child of div.thumbnail. I want to filter them out. I use as..

var i =0;
$("div.thumbnail :first-child").each(function() {
    console.log("Touch "+(++i)+" time(s) !");
    if($(this).context.nodeName.toLowerCase() == 'img') {
        console.log("Getting Image Tag.");
    }
});

My question is I want to filter in getting elements ..

$("div.thumbnail :first-child :img").each(function(){});

I don't want to iterate as count of div.thumbnail . I want to iterate as count of div.thumbnail with first child tag is img. How to figure it out ?

Upvotes: 2

Views: 301

Answers (3)

Rickyrock
Rickyrock

Reputation: 328

$(".thumbnail:has('> img:first-child'),.thumbnail > img:first-child").each(function(){
     //TO Do here
});

DEMO

Upvotes: 1

Itay
Itay

Reputation: 16777

Use the :has() Selector

$("div.thumbnail:has( > img:first-child)").each(function(){});

jsFiddle Demo

Upvotes: 2

Khawer Zeshan
Khawer Zeshan

Reputation: 9646

Simple

$(".thumbnail > img").each(function(){
    //
});

This will skip the following divs where first child is not an img

<div class = "thumbnail">
  <a href = "someLink"><img src = "somePath"></a>
</div>

FIDDLE

Upvotes: 1

Related Questions