javascript - How to add querySelectorAll() function to Element for IE <= 7? -


with code this article i've added queryselectorall document in ie7.

but need use on element rather document, this:

var containers = document.queryselectorall('.container');   // works (var i=0; i<=containers.length; i++) {     var container = containers[i];     container.queryselectorall('a[data-type="people"]');    // fails     // ... } 

is there way add queryselectorall elements in ie7 rather document?

very interesting question.

i lean toward using library this, jquery, 1 of ones mentioned below, closure, or any of several others. or using sizzle (the selector engine jquery uses in v1.9 branch).

but answering question asked:

you can't extend element prototypes on ie7 (sadly), unless want run of element instances through preprocessor function add queryselectorall them (the way prototype , mootools work, instance), you'll have have separate function pass element into.

here's 1 approach writing 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);         }         {             if (needsid) {                 element.id = "";             }         }     }      return qsaworker; })(); 

and of course, if want use qsaworker in browsers have queryselectorall, you'd want this:

function qsaworker(element, selector) {     return element.queryselectorall(selector); } 

so in total, then, you'd 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);         }         {             if (needsid) {                 element.id = "";             }         }     }      function qsaworkerwrap(element, selector) {         return element.queryselectorall(selector);     }      // return 1 browser wants use     return document.createelement('div').queryselectorall ? qsaworkerwrap : qsaworkershim; })(); 

your code using this:

var containers = document.queryselectorall('.container'); (var i=0; i<=containers.length; i++) {     var container = containers[i];     var links = qsaworker(container, 'a[data-type="people"]'); // <== changed     // ... } 

but again, tend lean toward using library...


Comments

Popular posts from this blog

c# - Operator '==' incompatible with operand types 'Guid' and 'Guid' using DynamicExpression.ParseLambda<T, bool> -