Notes From A Selector Engine

As pre­vi­ously stated, I’ve recently been work­ing on a selector engine. Unfor­tu­nately, as every browser behaves slightly dif­fer­ently, I’ve had to resort to con­struct­ing com­pat­ib­il­ity tables. See­ing as they can be use­ful in other applic­a­tions, I thought I’d post it here:

Element.querySelectorAll

A browser-native selector engine that allows you to select ele­ment nodes based on a CSS selector (for example: div p a).

var a = document.getElementById('a');

a.querySelectorAll('div.post > p a[class]');
IE6 IE7 IE8 Fire­fox 3 Fire­fox 3.5 Opera 9 Opera 10 Safari 3 Safari 4 Chrome 1 Chrome 2
no no no no yes no yes no yes yes yes

Element.firstElementChild / Element.lastElementChild / Element.previousElementSibling / Element.nextElementSibling

Selects the first/last ele­ment child or the previous/next ele­ment sib­ling. Saves on extrenu­ous code like:

var previous = document.getElementById('example');
while((previous = previous.previousSibling) !== null && previous.nodeType !== 1) { }
var a = document.getElementById('a');

a.firstElementChild;
a.lastElementChild;
a.previousElementSibling;
a.nextElementSibling;
IE6 IE7 IE8 Fire­fox 3 Fire­fox 3.5 Opera 9 Opera 10 Safari 3 Safari 4 Chrome 1 Chrome 2
no no no no yes yes yes yes yes yes yes

Element.children

Sim­ilar to the childNodes method, but without text nodes and comments.

var a = document.getElementById('a');

a.children;
IE6 IE7 IE8 Fire­fox 3 Fire­fox 3.5 Opera 9 Opera 10 Safari 3 Safari 4 Chrome 1 Chrome 2
almost (includes comments) almost (includes comments) almost (includes comments) no yes yes yes yes yes yes yes

Element.compareDocumentPosition

Allows you to com­pare one node’s pos­i­tion to another. Returns a bit­mask.

var a = document.getElementById('a');
var b = document.getElementById('b');

a.compareDocumentPosition(b);
IE6 IE7 IE8 Fire­fox 3 Fire­fox 3.5 Opera 9 Opera 10 Safari 3 Safari 4 Chrome 1 Chrome 2
no no no yes yes yes yes yes yes no yes

Element.contains

Returns a boolean whether or not an ele­ment is con­tained within another.

var a = document.getElementById('a');
var b = document.getElementById('b');

a.contains(b);
IE6 IE7 IE8 Fire­fox 3 Fire­fox 3.5 Opera 9 Opera 10 Safari 3 Safari 4 Chrome 1 Chrome 2
yes yes yes no no yes yes yes yes yes yes

Comments

No responses have been made so far. Add your comments.

    What do you think? Leave a comment...