Selectors-Child Filter
一、:first-child Selector
選擇第一個子元素。
如下範例中,在<div>元素底下選擇第一個子元素<p>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://code.jquery.com/jquery-3.0.0.js"></script> <meta name="viewport" content="width=device-width"> </head> <body> <div> <p>aaa</p> <p>bbb</p> <p>ccc</p> </div> <div> <p>aaa</p> <p>bbb</p> <p>ccc</p> </div> <script> $("div p:first-child").css("color", "red"); </script> </body> </html>
二、:first-of-type Selector
在每一組父子元素中,選出所指定元素的第一個。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://code.jquery.com/jquery-3.0.0.js"></script> <meta name="viewport" content="width=device-width"> </head> <body> <div> <p>aaa</p> <p>bbb</p> <p>ccc</p> </div> <div> <span>aaa</span> <p>bbb</p> <p>ccc</p> </div> <script> $("p:first-of-type").css("color", "red"); </script> </body> </html>
三、:last-child Selector
選擇最後一個子元素。
四、:last-of-type Selector
在每一組父子元素中,選出所指定元素的最後一個。
五、:nth-child() Selector
在每一組父子元素中,選擇第n個子元素(one-based)。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://code.jquery.com/jquery-3.0.0.js"></script> <meta name="viewport" content="width=device-width"> </head> <body> <div> <p>aaa</p> <p>bbb</p> <p>ccc</p> </div> <div> <span>aaa</span> <p>bbb</p> <p>ccc</p> </div> <script> $("p:nth-child(2)").css("color", "red"); </script> </body> </html>
六、:nth-last-child() Selector
從後面數起,選擇第n個子元素(one-based)。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://code.jquery.com/jquery-3.0.0.js"></script> <meta name="viewport" content="width=device-width"> </head> <body> <div> <p>aaa</p> <p>bbb</p> <p>ccc</p> <p>ddd</p> </div> <div> <span>aaa</span> <p>bbb</p> <p>ccc</p> <p>ddd</p> </div> <script> $("p:nth-last-child(2)").css("color", "red"); </script> </body> </html>
七、:nth-last-of-type() Selector
從後面數起,在每一組父子元素中,選出所指定元素的第n個。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://code.jquery.com/jquery-3.0.0.js"></script> <meta name="viewport" content="width=device-width"> </head> <body> <div> <p>aaa</p> <p>bbb</p> <span>ccc</span> <span>ddd</span> </div> <div> <p>aaa</p> <span>bbb</span> <span>ccc</span> <p>ddd</p> </div> <script> $("span:nth-last-of-type(2)").css("color", "red"); </script> </body> </html>
八、:nth-of-type() Selector
從前面數起,在每一組父子元素中,選出所指定元素的第n個。
九、:only-child Selector
在每一組父子元素中,選出底下只有一個的子元素。
十、:only-of-type Selector
在每一組父子元素中,選出底下該形態只有一個的子元素。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://code.jquery.com/jquery-3.0.0.js"></script> <meta name="viewport" content="width=device-width"> </head> <body> <div> <p>aaa</p> <p>bbb</p> <span>ccc</span> </div> <div> <p>aaa</p> <span>bbb</span> <span>ccc</span> <p>ddd</p> </div> <script> $("span:only-of-type").css("color", "red"); </script> </body> </html>