Document. querySelector () and document. querySelectorAll ()

Source: Internet
Author: User

In css, setting styles for specific elements is inseparable from the use of delimiters. Currently, some large javascript frameworks often use delimiters to obtain specific elements, such as jQuery. The W3c standard defines two new methods (querySelectorAll and querySelectorAll) to obtain element nodes. Both methods accept the selector as their own parameters. In his book "High Performance JavaScript", Nicolas briefly introduced these two methods and compared their Performance. Compared with the traditional method of getting element nodes, its performance is superior. Let's start with the example below.

<table id="score">  <thead>    <tr>      <th>Test</th>      <th>Result  </th>  </tr>  </thead>  <tfoot>    <tr>      <th>Average  </th>      <td>82%  </td></tr></tfoot>  <tbody>    <tr>      <td>A</td>      <td>87%</td></tr>   <tr>      <td>A</td>      <td>87%</td></tr><tr>      <td>A</td>      <td>87%</td></tr>…</tbody></table>

In the above 1000 rows table, to obtain the cells with scores in each row, we use the following methods in the traditional sense:

var table = document.getElementById("score");var groups = table.tBodies;var rows = null;var cells = [];for (var i = 0; i < groups.length; i++) {  rows = groups[i].rows;  for (var j = 0; j < rows.length; j++) {    cells.push(rows[j].cells[1]);  }}

With the new method provided by w3c, you can complete the task with only one line of code, and the speed is very fast.

var cells = document.querySelectorAll("#score>tbody>tr>td:nth-of-type(2)");

We can use a method Performance Analyzer provided in javascript design patterns to compare the performance of these two methods. The method is as follows:

var MethodProfiler = function(component) {  this.component = component;  this.timers = {};  this.log = document.createElement("ul");  var body = document.body;  body.insertBefore(this.log,body.firstChild);  for(var key in this.component) {    // Ensure that the property is a function.    if(typeof this.component[key] !== 'function') {      continue;    }    // Add the method.    var that = this;    (function(methodName) {      that[methodName] = function() {        that.startTimer(methodName);        var returnValue = that.component[methodName].apply(that.component,          arguments);        that.displayTime(methodName, that.getElapsedTime(methodName));        return returnValue;      };    })(key); }};MethodProfiler.prototype = {  startTimer: function(methodName) {    this.timers[methodName] = (new Date()).getTime();  },  getElapsedTime: function(methodName) {    return (new Date()).getTime() - this.timers[methodName];  },  displayTime: function(methodName, time) {  var li = document.createElement("li");var text = document.createTextNode(methodName + ': ' + time + ' ms');    li.appendChild(text);this.log.appendChild(li);  }};

Then write the two methods into an object and compare them with the Performance Analyzer.

var obj = {getElementByTradition:function(){var table = document.getElementById("score");var groups = table.tBodies;var cells = [];for (var i = 0; i < groups.length; i++) {  rows = groups[i].rows;  for (var j = 0; j < rows.length; j++) { cells.push(rows[j].cells[1]);   } } }, querySelectorAll:function(){ var cells = document.querySelectorAll("#score>tbody>tr>td:nth-of-type(2)");}}var obj = new MethodProfiler(obj);obj.getElementByTradition();obj.querySelectorAll();

Looking at the example, we can clearly see that the new method is not only simple, but also superior to our traditional method in performance. Note that although IE8 supports these methods, IE8 does not support the nth-of-type () selector (for details, see Compatibility table: CSS3 Selectors ), therefore, an error message is thrown in IE8.

When the document. querySelectorAll () method is called, the first element node of several types of nodes is returned. If no matching node exists, null is returned, for example:

<div id="fooid=">      <p class=id="warningid=">This is a sample warning</p>      <p class=id="errorid=">This is a sample error</p> </div> <div id=id="barid=">      <p>...</p> </div>

Use the preceding html and call the following method to return the element whose id attribute is foo.

var obj = document.querySelector("#foo, #bar");alert(obj.innerHTML);//foo

If the element whose id attribute is foo is removed, bar is returned when the above method is called. This method is searched based on the selector passed in the parameter. If it is found, it is terminated and this element is returned. Otherwise, null is returned.

Call the document. querySelectorAll () method to return all matching elements contained in the node tree in sequence, such:

var res = document.querySelectorAll("p.warning, p.error");

In the above res, select all p elements whose class is "error" or "warning" in the ze document.

Although these two methods are easy to use and have high performance, only limited browsers support these methods, such as IE8, FF3.5, Safari3.1, chrome1, and opera10. We can try to use them in some applications as follows:

If (document. querySelector) {var res = document. querySelectorAll ("p. warning, p. error") ;}else {// traditional method ;}

This article only briefly discusses these two methods. For more information, see w3c.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.