1. 程式人生 > >JQuery選擇器之CSS選擇器

JQuery選擇器之CSS選擇器

核心選擇器

語法 描述
* 選擇所有元素
<type> 選擇特定型別的元素
.<class> 選擇具有特定class的元素
<type>.<class> 選擇具有特定class的某類元素
‘#id 選擇具有特定id屬性值的元素

屬性選擇器

語法 描述
[attr] 選取定義了attr屬性的元素,即使這個屬性值為空
[attr=”val”] 選擇attr屬性值等於字串val的元素
[attr^=”val”] 選擇attr屬性值以字串val開頭的元素
[attr$=”val”] 選擇attr屬性值以字串val結尾的元素
[attr*=”val”] 選擇attr屬性值包含字串val的元素
[attr~=”val”] 選擇attr屬性值包含多個空格分割的多個值,且其中一個值等於字串val的元素
[attr1=”val”] 選擇attr屬性值等於字串val,或屬性值為連字元分割的值列表且第一個值是字串val的元素

關係選擇器

語                                  法 描述
<selector> <selector> 選擇第一個選擇器匹配元素內匹配第二個選擇器的後代元素
<selector> > <selector> 選擇第一個選擇器匹配元素內匹配第二個選擇器的直接子元素
<selector> + <selector> 選擇第一個選擇器匹配元素內匹配第二個選擇器的下一個兄弟元素
<selector> ~<selector> 選擇第一個選擇器匹配元素內匹配元素之後的匹配第二個選擇器的所有兄弟元素

示例

  • $(“div”) selects all <div> elements
  • $(“fieldset a”) selects all <a> elements within <fieldset> elements
  • $(“li>p”) selects all <p> elements that are direct children of <li> elements
  • $(“div~p”) selects all <div> elements that are preceded by a <p> element
  • $(“p:has(b)”) selects all <p> elements that contain a <b> element
  • $(“div.someClass”) selects all <div> elements with a class name of someClass
  • $(“.someClass”) selects all elements with class name someClass
  • $(“#testButton”) selects the element with the id value of testButton
  • $(“img[alt]”) selects all <img> elements that possess an alt attribute
  • (a[href$=.pdf]”) selects all <a> elements that possess an href attribute that ends in .pdf
  • $(“button[id*=test]”) selects all buttons whose id attributes contain test