javascript進階選取器querySelector和querySelectorAll

來源:互聯網
上載者:User

標籤:chrome   log   element   name   javascrip   length   不同的   ring   規範   

querySelector 和 querySelectorAll 方法是 W3C Selectors API 規範中定義的。他們的作用是根據 CSS 選取器規範,便捷定位文檔中指定元素。

目前幾乎主流瀏覽器均支援了他們。包括 IE8(含) 以上版本、 Firefox、 Chrome、Safari、Opera。

querySelector 和 querySelectorAll 在規範中定義了如下介面:

module dom { [Supplemental, NoInterfaceObject] interface NodeSelector { Element querySelector(in DOMString selectors); NodeList querySelectorAll(in DOMString selectors); }; Document implements NodeSelector; DocumentFragment implements NodeSelector; Element implements NodeSelector; };

 

從介面定義可以看到Document、DocumentFragment、Element都實現了NodeSelector介面。即這三種類型的元素都擁有者兩個方法。querySelector和querySelectorAll的參數須是符合 css selector 的字串。不同的是querySelector返回的是一個對象,querySelectorAll返回的一個集合(NodeList)。

擷取頁面I屬性D為test的元素:

  1. document.getElementById("test");
  2. //or
  3. document.querySelector("#test");
  4. document.querySelectorAll("#test")[0];

擷取頁面class屬性為”red”的元素:

  1. document.getElementsByClassName(‘red‘)
  2. //or
  3. document.querySelector(‘.red‘)
  4. //or
  5. document.querySelectorAll(‘.red‘)

 

Element.querySelector和Element.querySelectorAll和jQuery(element).find(selector)選取器的區別:
  1. <divid="test1"><ahref="http://www.hujuntao.com/">設計蜂巢</a></div>
  2. <pid="bar">111</p>
  3. <script>
  4. var d1 = document.getElementById(‘test1‘),
  5. obj1 = d1.querySelector(‘div a‘),
  6. obj2 = d1.querySelectorAll(‘div a‘);
  7. obj3 = $(d1).find(‘div a‘);
  8. console.log(obj1)//<a href="http://www.hujuntao.com/">設計蜂巢</a>
  9. console.log(obj2.length)//1
  10. console.log(obj3)//null
  11. </script>

querySelectorAll 在文檔內找全部符合選取器描述的節點包括Element本身
jQuery(element).find(selector) 在文檔內找全部符合選取器描述的節點不包括Element本身

javascript進階選取器querySelector和querySelectorAll

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.