开发者

Is there a better way to find a single element by class with jQuery?

开发者 https://www.devze.com 2023-03-24 12:47 出处:网络
I often find myself building a list item row or something by grabbing a template, cloning it, setting it to a variable, and using find(\'.class\') to find elements under it, and then assigning them un

I often find myself building a list item row or something by grabbing a template, cloning it, setting it to a variable, and using find('.class') to find elements under it, and then assigning them unique ids and otherwise working with them before appending the list item to whatever list I'm doing.

For example, if I have a list of items, all of which are set from a template, and include sub items, which are specified by class, I would do something like this (not tested, just a process example):

// Create my list item.
$ListItem = $('#list_item_template').clone();

// Set the id for the first field so I can work with it directly later.
$ListItem.find('.field_one).attr('id', 'field_one_'+ListItemID).val('field one value for this list item');

// Set the id for the second field so I can work with it directly later.
$ListItem.find('.field_two).attr('id', 'field_two_'+ListItemID).val('field two value for this list item');

// Add the i开发者_Python百科tem to the list
$ListItem.appendTo($List);

Now, I can access the first "field" of the Xth list item like $('#field_one_[ListItemID].

The problem is, even though I'm specifying the $ListItem, I know that when I use find('.field_one') to find the field to add an id, it traverses every element in the template looking for that class. This isn't much of a performance hit, but if it's a long list, or a long template, it will add up.

Is there a more effective way to do this? Something like you would expect from a function called .findOnce()....?

Thanks!


It depends on how your DOM is setup. children() is faster than find(), for example, just like parent() is faster than parents().

Example: $ListItem.children('.field_one')


You can use the :first selector

http://api.jquery.com/first-selector/

$ListItem.find('.field_one:first') ....

Personally, I don't put $ as the prefix on js variables. It will confuse with $ from jquery.

just use var ListItem


I'm not sure you need to assign an ID to it at all. Can you instead refer to the item via $ListItem.find('.field').index(0) or use an nth-child selector $ListItem.find('.field:nth-child(1)').

0

精彩评论

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

关注公众号