简体   繁体   中英

jquery - mix variable referencing a dom element with selector

I usually create variables for frequently reused DOM elements like this:

var $dom_element = $('#dom_element);

where this is my setup:

<div id="dom_element">
  <div class="child_element">
  <div class="child_element">
</div>

what I'm wondering is if I can mix this variable with a subselector to get child elements. I guess it would be something like this:

var $child_element = $($dom_element + ' .child_element);

And if so, is there any speed benefit to doing this versus just saying:

$('.child_element);

considering the fact that both of these elements might be deeply nested in a large site?

With

var $dom_element = $('#dom_element);

I would use the following to get the child elements

var $child_element = $dom_element.find(".child_element");//I prefer this one, it is easier to read.

or

var $child_element = $(".child_element", $dom_element);

From my research/reading, it appears that setting an element to a variable is best if you are going to reference it many times. That way jQuery does not have to search the DOM many times.

Regarding your selectors, you can get yourself into trouble when using a bare class as a child selector. What if you have multiple child nodes using that same class?

.find() works, as others have suggested. You could alternatively use .children():

var $kids = $dom_element.children('.child_element');

http://api.jquery.com/children/

The difference between .find() and .children() is that .children() will only look one level down the DOM tree. .find() will recursively run through all possible child nodes to match your selector.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM