Question

I want to see if a element is sat inside another one, I do this a lot of times in my app like this:

is_inside_something: function(element){
    return element.closest(".something").length == 1
}

So I'm see if there's an parent called is returned for ".something"

The problem I've noticed webpages slowing down and when I take a look at the webkit profiler it's this bit of code that's doing it.

Is there a quicker way of saying:

"Does the class '.something" exist as a parent of this element at all?"

It seems that this is taking up so much memory because it goes up through the while dom of the page all the way up to the head every time it's called. Which is a lot in my case.

Was it helpful?

Solution

Try to use pure javascript and limit the number of DOM climb-up iterations:

var ctr=0;
var is_in_something=function(element,steps){
    if(ctr<steps){
    if($(element.parentNode).hasClass(".something")){
        return true;
    }else{
        ctr++;
        return is_in_something(element.parentNode,steps);
    }
    }else{
        return false;
    }
}

is_in_something(document.getElementById("mydiv"),20);

The above code will try to check the 20 parents of "mydiv". It will return true if one of the parent has the class ".something". If after 20 iterations no such parent is found, then it will return false.

So, with this you can control the number of levels you want to climb-up the DOM and not having to reach the HEAD everytime.

OTHER TIPS

There is also the "parents" function depending on your context I think it helps. Here is a performance test

http://jsperf.com/jquery-parents-vs-closest/2

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top