How to get the children of the $(this) selector?

2018-12-31 07:18发布

I have a layout similar to this:

<div id="..."><img src="..."></div>

and would like to use a jQuery selector to select the child img inside the div on click.

To get the div, I've got this selector:

$(this)

How can I get the child img using a selector?

16条回答
笑指拈花
2楼-- · 2018-12-31 07:57

Here's a functional code, you can run it (it's a simple demonstration).

When you click the DIV you get the image from some different methods, in this situation "this" is the DIV.

$(document).ready(function() {
  // When you click the DIV, you take it with "this"
  $('#my_div').click(function() {
    console.info('Initializing the tests..');
    console.log('Method #1: '+$(this).children('img'));
    console.log('Method #2: '+$(this).find('img'));
    // Here, i'm selecting the first ocorrence of <IMG>
    console.log('Method #3: '+$(this).find('img:eq(0)'));
  });
});
.the_div{
  background-color: yellow;
  width: 100%;
  height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="my_div" class="the_div">
  <img src="...">
</div>

Hope it helps!

查看更多
宁负流年不负卿
3楼-- · 2018-12-31 07:58

If you need to get the first img that's down exactly one level, you can do

$(this).children("img:first")
查看更多
有味是清欢
4楼-- · 2018-12-31 07:59

The jQuery constructor accepts a 2nd parameter called context which can be used to override the context of the selection.

jQuery("img", this);

Which is the same as using .find() like this:

jQuery(this).find("img");

If the imgs you desire are only direct descendants of the clicked element, you can also use .children():

jQuery(this).children("img");
查看更多
君临天下
5楼-- · 2018-12-31 07:59

Also this should work:

$("#id img")
查看更多
姐姐魅力值爆表
6楼-- · 2018-12-31 08:00

The direct children is

$('> .child', this)
查看更多
时光乱了年华
7楼-- · 2018-12-31 08:01

Ways to refer to a child in jQuery. I summarized it in the following jQuery:

$(this).find("img"); // any img tag child or grandchild etc...   
$(this).children("img"); //any img tag child that is direct descendant 
$(this).find("img:first") //any img tag first child or first grandchild etc...
$(this).children("img:first") //the first img tag  child that is direct descendant 
$(this).children("img:nth-child(1)") //the img is first direct descendant child
$(this).next(); //the img is first direct descendant child
查看更多
登录 后发表回答