Home >Web Front-end >JS Tutorial >jQuery: Problems with using the first-child selector

jQuery: Problems with using the first-child selector

黄舟
黄舟Original
2017-06-23 14:29:541226browse

jQuery:Usage issues of first-child

<ul>
<li>Test1<li>
<li>aaaaa<li>
<li>bbbbb<li>
</ul>

<ul>
<li>Test2<li>
<li>ccccc<li>
<li>ddddd<li>
</ul>

Use first-child to remove the 25edfb22a4f469ecb59f1190150159c6 from each ff6d136ddc5fdfeffaf53ff6ee95f185 For elements, using first will not work. clear?

In jQuery's child element filter selector, you need to pay attention to the use of :first-child. The example in the document is used like this:

$("ul li:first-child").addClass("highlight");


The function it implements is to obtain the first li element under all uls, which is different from:first.

$("ul li:first").addClass("highlight");


:first only gets the first li in a ul, provided that there are 2 ul lists in the page.

For:

$("ul li:first-child").addClass("highlight");

You can use another way of writing, with the same effect. Of course, I think the latter is easier to understand, because it selects the first sub-element under ul:
$("ul :first-child").addClass("highlight");
You need to pay attention to the spaces in the above examples.


$(function(){
  //$("ul li:first-child").addClass("highlight");
  //$("ul :first-child").addClass("highlight"); //和上面效果一样 注意空格
  $("ul :nth-child(2n)").addClass("highlight");
  //$(".one .mini:nth-child(2)").addClass("highlight"); //和下面一样效果
  //$(".one :nth-child(2)").addClass("highlight");
 
  //$(".one .mini:last-child").addClass("highlight"); //和下面一样效果
  $(".one :last-child)").addClass("highlight");
});

The above is the detailed content of jQuery: Problems with using the first-child selector. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn