Very interesting question.
I would lean toward using a library for this, like jQuery, one of the ones mentioned below, Closure, or any of several others. Or just using Sizzle (the selector engine jQuery uses in the v1.9 branch).
But answering the question you actually asked:
You can't extend element prototypes on IE7 (sadly), so unless you want to run all of your element instances through a preprocessor function to add querySelectorAll
to them (the way Prototype and MooTools work, for instance), you'll have to have a separate function you pass the element into.
Here's one approach to writing that function:
var qsaWorker = (function() {
var idAllocator = 10000;
function qsaWorker(element, selector) {
var needsID = element.id === "";
if (needsID) {
++idAllocator;
element.id = "__qsa" + idAllocator;
}
try {
return document.querySelectorAll("#" + element.id + " " + selector);
}
finally {
if (needsID) {
element.id = "";
}
}
}
return qsaWorker;
})();
And of course, if you want to use qsaWorker
in browsers that have querySelectorAll
, you'd want this:
function qsaWorker(element, selector) {
return element.querySelectorAll(selector);
}
So in total, then, you'd probably want:
var qsaWorker = (function() {
var idAllocator = 10000;
function qsaWorkerShim(element, selector) {
var needsID = element.id === "";
if (needsID) {
++idAllocator;
element.id = "__qsa" + idAllocator;
}
try {
return document.querySelectorAll("#" + element.id + " " + selector);
}
finally {
if (needsID) {
element.id = "";
}
}
}
function qsaWorkerWrap(element, selector) {
return element.querySelectorAll(selector);
}
// Return the one this browser wants to use
return document.createElement('div').querySelectorAll ? qsaWorkerWrap : qsaWorkerShim;
})();
Your code using it would then look like this:
var containers = document.querySelectorAll('.container');
for (var i=0; i<=containers.length; i++) {
var container = containers[i];
var links = qsaWorker(container, 'a[data-type="people"]'); // <== Changed
// ...
}
But again, I would tend to lean toward using a library...