querySelector and querySelectorAll

javascript advance selector

Define in W3C Selectors API, used to locate element in document by CSS rule.

IE >= 8, Firefox, Chrome, Safari, Opera support them.

1
2
3
4
5
6
7
8
9
10
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 implements NodeSelector interface.
The difference is querySelector return an object, querySelectorAll return a collection(NodeList).

1
2
3
document.getElementById("test");
document.querySelector("#test");
document.querySelectorAll("#test")[0];
1
2
3
document.getElementsByClassName('red')
document.querySelector('.red')
document.querySelectorAll('.red')

Difference between jQuery(element).find(selector)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<div id="test1"><a href="http://www.linchenguang.com/">lcg</a></div>
<p id="bar">I'm a bar</p>

<script>
var d1 = document.getElementById('test1'),
obj1 = d1.querySelector('div a'),
obj2 = d1.querySelectorAll('div a');
obj3 = $(d1).find('div a');
//<a href="http://www.linchenguang.com/">lcg</a>
console.log(obj1)
//1
console.log(obj2.length)
//null
console.log(obj3)
</script>

querySelectorAll find element in DOM, contain Element it’s self.
jQuery(element).find(selector) find element in DOM, not contain Element it’s self.