Home >Web Front-end >JS Tutorial >jquery: Why is the first-child selector invalid in this case?

jquery: Why is the first-child selector invalid in this case?

黄舟
黄舟Original
2017-06-23 14:32:401709browse

Why does the first-child in jQuery fail to take effect if there is an additional h2 tag? See picture below. Thank you

<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js">
</script>
<script type="text/javascript"> $(document).ready(function(){
$(&#39;div p:first-child&#39;).css(&#39;backgroundColor&#39;, &#39;#555&#39;);
});
</script>	
</head>
<body>
<html>
<div>
    <h2>hello</h2>
    <p>A</p>
    <p>B</p>
    <p>C</p>
    </div>
    <div>
    <p>D</p>
    <p>E</p>
    <p>F</p></div>
    <div>
    <p>G</p>
    <p>H</p>
    <p>I</p>
    </div>
    </body>
    </html>

jquery: Why is the first-child selector invalid in this case?

first-child will only traverse to the first child element

Because there is no first and p in the first div Element

$("div > p").first()

but the p tag is selected, not h2?

$("div > p").first()

No. Only A has an effect, D and G have no effect.

nth-of-type

The above is the detailed content of jquery: Why is the first-child selector invalid in this case?. 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