Question

Which is the best way to find all elements from page which match the size i need, and less browser overloading ?

the most important thing is to make it so that the browser will not overload and will not crash if on page are a lot of elements.

what i'm using now is:

elements = document.getElementsByTagName("*");
len = elements.length; 
for(var i = 0; i < len; i++) 
    if(elements[i].clientHeight == MyHeight && elements[i].clientWidth == MyWidth)
{ /*my code*/ }

Please, if anybody knows a better way which don't stress the browser as much as what I'm using now, then this is what i need.

Was it helpful?

Solution

If you absolutely have to do it, it would be more efficient to iterate through the tree recursively, because then once you hit an element that is less than what you need, you know nothing inside of it can be the required size. Still seems like there would be a better solution under most circumstances, but I don't know your specific problem.

EDIT:

This works.

function findElements( width, height, element ){
    var results = Array();

    for( var i=0; i<element.childNodes.length; i+=1 ){
        var childElement = element.childNodes[i];

        if( childElement.clientWidth == width && childElement.clientHeight == height ){
            results.push(childElement);
            results = results.concat(findElements(width, height, childElement));

        } else if( childElement.clientWidth < width || childElement.clientHeight < height ){
            continue;

        } else {
            results = results.concat(findElements(width, height, childElement));
        }
    }

    return results;
}

findElements(myWidth, myHeight, document);

OTHER TIPS

I think we are talking about speed here.(though the difference is marginal).

Who is the fastest??? -->click the run button and test it your self!!!

I guess document.body.querySelectorAll("*"); is a clear winner.

var items = document.body.querySelectorAll("*");
     var target, i, len = items.length;
     for (i=0;i<len;i++) {
       target=items[i];
if(//your condition)
    { and the code}

Winner!!!

**Conclusion:**Just write code which are understandable,readable and elegant.I think understanding the logic is the most trivial part.

UPDATE:

function findParentNode() {

    var testObj = document.body.querySelectorAll("*");;
    for(var i=0;i<=testObj.length;i++){
      if(testobj.offsetWidth=="your width" && testobj.offsetHeight=="your height"){
            //push it in an array or do whatever you wanted to do 
          }
     else{
     //no elements found!!!
     }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top