2

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 ?

3 Answers 3

2

Use the :has() Selector

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

jsFiddle Demo

Sign up to request clarification or add additional context in comments.

1 Comment

I also got with your answer ! Cheer .. :) now. Thanks.
1

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

4 Comments

He's trying to get the parents not the children
I'm just saying you asked in the Original Post how to iterate the parents, and this code is iterating the children.
@Itay , Thanks for guiding me. And I asked I want to iterate img tags.
According to the parents... You said it specifically
1
$(".thumbnail:has('> img:first-child'),.thumbnail > img:first-child").each(function(){
     //TO Do here
});

DEMO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.