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

With the code for this article, I successfully added querySelectorAll to a document in IE7.

But I need to use it for an element, not for document , for example:

 var containers = document.querySelectorAll('.container'); // Works for (var i=0; i<=containers.length; i++) { var container = containers[i]; container.querySelectorAll('a[data-type="people"]'); // Fails // ... } 

Is there a way to add querySelectorAll to elements in IE7, and not just to document ?

+4
source share
1 answer

Very interesting question.

I would be inclined to use a library for this, for example jQuery , one of the following, Closure , or any of several others . Or just using Sizzle (jQuery selection mechanism is used in v1.9 branch).

But answering the question that you actually asked:

You cannot extend element prototypes to IE7 (unfortunately), so if you do not want to run all instances of elements through the preprocessor function to add querySelectorAll to them (the Prototype and MooTools path, you will have to have a separate function to which you pass the element .

Here is one approach to writing this 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 with querySelectorAll , you need the following:

 function qsaWorker(element, selector) { return element.querySelectorAll(selector); } 

So, in general, you probably want to:

 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, will 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 tend to use the library ...

+7
source

Source: https://habr.com/ru/post/1480073/


All Articles