Home >Web Front-end >JS Tutorial >jquery: Why is the first-child selector invalid in this case?
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(){ $('div p:first-child').css('backgroundColor', '#555'); }); </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>
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!