开发者

Selecting element by id from jQuery collection

How to select an element by id from a jquery collection?

e.g.

var jQObj = $("div");
开发者_JS百科

How to access a div with id say div_1_1 from the collection jQObj?

Thanks


It depends on the structure within jQQbj.
If #div_1_1 is on the "top level" you need to invoke .filter():

var $myDiv = jQQj.filter('#div_1_1');

wheres if div_1_1 is somewhere as childnode invoke .find():

var $myDiv = jQQj.find('#div_1_1');

Reference: .filter(), .find()


Try this:

$("#div_1_1", jQObj);


var divs = $('div');
var myDiv = divs.filter('#singleDiv');


Why do you want to filter it in that way? Is that block of code in the middle of a mad jQuery chain you don't want to break?

Just curious because ID selectors are fast (especially compared to running your collection through $.fn.filter) so I don't quite get the aversion to re-querying the DOM.

I put up a quick jsperf test here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜