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:40

$(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>

查看更多
弹指情弦暗扣
3楼-- · 2018-12-31 07:48

You can use Child Selecor to reference the child elements available within the parent.

$(' > img', this).attr("src");

And the below is if you don't have reference to $(this) and you want to reference img available within a div from other function.

 $('#divid > img').attr("src");
查看更多
唯独是你
4楼-- · 2018-12-31 07:50

You could also use

$(this).find('img');

which would return all imgs that are descendants of the div

查看更多
若你有天会懂
5楼-- · 2018-12-31 07:50

Try this code:

$(this).children()[0]
查看更多
残风、尘缘若梦
6楼-- · 2018-12-31 07:53

Without knowing the ID of the DIV I think you could select the IMG like this:

$("#"+$(this).attr("id")+" img:first")
查看更多
长期被迫恋爱
7楼-- · 2018-12-31 07:57

You can use either of the following methods:

1 find():

$(this).find('img');

2 children():

$(this).children('img');
查看更多
登录 后发表回答