开发者

Selecting element by id from jQuery collection

开发者 https://www.devze.com 2023-03-19 09:39 出处:网络
How to select an element by id from a jquery collection? e.g. var jQObj = $(\"div\"); 开发者_JS百科

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

精彩评论

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