[CSS] Selectors API

You know jQuery uses CSS selectors to query the elements in DOM. This mechanism is known as “Selectors API“. “Selectors API Level 1” is W3C Recommendation as of Feb/21/2013. “Selectors API Level 2” is included in “DOM 4” (2015).

 

1. Selectors API Level1

Most browsers (IE8+) already support Selectors API Level1

partial interface Document {
  Element? querySelector(DOMString selectors);
  NodeList querySelectorAll(DOMString selectors);
};

partial interface DocumentFragment {
  Element? querySelector(DOMString selectors);
  NodeList querySelectorAll(DOMString selectors);
};

partial interface Element {
  Element? querySelector(DOMString selectors);
  NodeList querySelectorAll(DOMString selectors);
};

CSS selectors can be called from the Document or Elements.

  • querySelector() : returns the first matching element
  • querySelectorAll() : returns the list of elements

 

2.  querySelector()

The method is defined in the “document” object.

<button id="testBtn">Press</button><br />
<div id="div1">
  <div id="div2"></div>
</div>

You can access the element with “querySelector()” from the document object.

var btnElement = document.querySelector("#testBtn");
btnElement.addEventListener("click", function (e) {
  var div2Element = document.querySelector("#div2");
  div2Element.innerHTML = "Hello World";
  e.preventDefault();
});

The “querySelector()” method can be called from the element too.

btnElement.addEventListener("click", function (e) {
  var div1Element = document.querySelector("#div1");
  var div2Element = div1Element.querySelector("#div2");
  div2Element.innerHTML = "Hello, World";
  e.preventDefault();
});

 

3. querySelectorAll()

<button id="testBtn">Press</button><br />
<div id="div1">
  Colors:
  <ul>
    <li class="item"></li>
    <li class="item"></li>
    <li class="item"></li>
  </ul>
</div>

The “querySelectorAll()” method returns an array of elements.

var colors = ["White", "Black", "Red", "Green", "Blue"];

var btnElement = document.querySelector("#testBtn");

btnElement.addEventListener("click", function (e) {
  var liElements = document.querySelectorAll(".item");
  for (var i = 0; i < liElements.length; i++) {
    liElements[i].innerHTML = colors[i];
  }
  e.preventDefault();
});

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s