Home > Web Front-end > JS Tutorial > body text

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

黄舟
Release: 2017-06-23 14:32:40
Original
1691 people have browsed it

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>
Copy after login

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()
Copy after login

but the p tag is selected, not h2?

$("div > p").first()
Copy after login

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

nth-of-type
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!