close

轉自 http://stackoverflow.com/questions/306583/this-selector-and-children

問題: div裡頭有一張圖, 目前抓到div, 要如何選擇到裡頭的圖片?

答案: $(this).find("img"); 或是 $(this).children("img");

--

I'd like to use a selector to select the child img of the div I'm clicking on this example:

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

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

$(this)

How do I get the img with a selector?

link|improve this question

77% accept rate
feedback

6 Answers

up vote831down voteaccepted

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

jQuery("img", this);

Which is the same as

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

If the imgs are direct descendants of the clicked element, you can also use:

jQuery(this).children("img");
link|improve this answer
28  
+1 Thanks, didn't know about this – Andreas Grech Sep 6 '09 at 7:57
212  
for what it's worth: jQuery("img", this) is internally converted into: jQuery(this).find("img") So the second is ever so slightly faster. :) – Paul Irish Jan 8 '10 at 23:49
5  
Thanks @Paul, I was worried that using find() was wrong, turns out it's the only way ;) – Agos Feb 17 '10 at 11:36
Thanks, Simon. Big help. – Chris Cummings Aug 8 '10 at 4:03
3  
@adamyonk infact not, atleast not if this is anything to go by: jsperf.com/jquery-children-vs-find/3 – Simon Skov Boisen Oct 13 '11 at 6:21
show 1 more comment
feedback

--

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 dizzy03 的頭像
    dizzy03

    碎碎念

    dizzy03 發表在 痞客邦 留言(0) 人氣()