Selectors-Hierarchy
一、Child Selector (“parent > child”)
指定parent元素底下一層必須是child元素。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <script src="https://code.jquery.com/jquery-3.0.0.js"></script> </head> <body> <div> <p>aaa</p> </div> <div> <span>bbb</span> </div> <script> $("div > p").css("color", "red"); </script> </body> </html>
二、Descendant Selector (“ancestor descendant”)
只要父元素是ancestor,而不管是子元素或是下n層孫元素是descendant,都符合選取條件。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <script src="https://code.jquery.com/jquery-3.0.0.js"></script> </head> <body> <div> <p>aaa <span>bbb</span>ccc</p> </div> <div> ddd </div> <script> $("div span").css("color", "red"); </script> </body> </html>
三、Next Adjacent Selector (“prev + next”)
選取符合prev元素而緊鄰他的下一個是兄弟next元素(注意不是子元素)的條件。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <script src="https://code.jquery.com/jquery-3.0.0.js"></script> </head> <body> <div> <p>aaa</p> <span>bbb</span> </div> <div> <span>ccc</span> <p>ddd</p> </div> <script> $("p + span").css("color", "red"); </script> </body> </html>
四、Next Siblings Selector (“prev ~ siblings”)
只要是兄元素是prev,而弟元素是siblings皆可選到(可不用緊鄰),
只要是同階層,並被指定的元素名稱都可以被選到。
<!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.0.0.js"></script> </head> <body> <div> <p>Paragraph 1 in the div.</p> <p>Paragraph 2 in the div.</p> </div> <p>Paragraph 3. Not in a div.</p> <p>Paragraph 4. Not in a div.</p> <script> $("div ~p").css("background", "yellow"); </script> </body> </html>
請參考CSS-基本格式與選擇器(Selector)的第四項第5點。