While it is not as pretty as querySelectorAll (which has a lot of problems), here is a very flexible function that recurses the DOM and should work in most browsers (old and new). As long as the browser supports your condition (i.e.: data attributes), you can get the item.
Curious: don't bother testing this and QSA on jsPerf. Browsers such as Opera 11 cache the query and distort the results.
the code:
function recurseDOM(start, whitelist) { var i = 0, startIsNode = !!start && !!start.nodeType, startHasChildNodes = !!start.childNodes && !!start.childNodes.length, nodes, node, nodeHasChildNodes; if(startIsNode && startHasChildNodes) { nodes = start.childNodes; for(i;i<nodes.length;i++) { node = nodes[i]; nodeHasChildNodes = !!node.childNodes && !!node.childNodes.length; if(!whitelist || whitelist[node.nodeType]) {
Then you can run it with the following:
recurseDOM(document.body, {"1": 1}); for speed or just recurseDOM(document.body);
Example with your specification: http://jsbin.com/unajot/1/edit
An example with a different specification: http://jsbin.com/unajot/2/edit
user1385191 Aug 16 '11 at 10:24 2011-08-16 22:24
source share