开发者

Jquery child selector vs. .each

开发者 https://www.devze.com 2023-03-25 23:45 出处:网络
Given the following example table: <ul class=\"topnav\"> <li>Item 1</li> <li>Item 2</li>

Given the following example table:

<ul class="topnav">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>

What are the differences between:

$selector1 = $('ul.topnav > li');

a开发者_开发问答nd

$selector2 = $('ul.topnav').each();

EDIT:

$selector2 = $('ul.topnav li').each();


The first will contain all li's which are a direct child of ul.topnav, the second will contain all ul.topnav elements.


Jquery child selector vs. .each


$('ul.topnav > li') will select all <li>s directly under the ul.

each should take a function as a parameter, and iterate over all matched <ul> - it doesn't not take the children <li>s. If anything, you want $('ul.topnav').children(), which is identical if the ul only contains li elements anyway.

For example, this will alert the number of children each list has (in your case, only the number 3)

$selector2 = $('ul.topnav').each(function(){
   alert($(this).children().length);
});

Also see the jquery API.


The second one will evaluate them individually, whereas the first one will evaluate them as a group

0

精彩评论

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