Javascript – JQuery: How to cache DOM

javascriptjqueryoptimization

I used Firefug to profile my web application and found that the following function is called, and needs to be called, literally hundreds of times per user visit. So I want to optimize it since Firebug says it uses the most resources/times.

function highlightChildDiv(parentDiv) {

    /* find the closest (hlisting) home listing to the middle of the scrollwindow & highlight */    
    var scrollElemPos = parentDiv.offset();
    var highlightDiv = $(document.elementFromPoint(
        scrollElemPos.left + parentDiv.width()  / 2,
        scrollElemPos.top  + parentDiv.height() / 2)
    ).closest('#parentDiv div.childClass');

    if (highlightDiv.hasClass("HighlightRow")) { 
        return; // if the div is already highlighted, return
    } else {
        $('#parentDiv div.childClass').removeClass("HighlightRow");
        highlightDiv.addClass('HighlightRow');
    }
}

Seems to me that one of the most un-optimized statements is .closest('#parentDiv div.childClass');, but I'm sure there is other things to improve.

Question: Does anyone have any JQuery performance tips on how I can optimize the code above given that this function is run literally hundreds of times per user visit.

Best Solution

First thought, eliminate the dead statement in the if clause.

if (!highlightDiv.hasClass("HighlightRow")) {  
    $('#parentDiv div.childClass').removeClass("HighlightRow"); 
    highlightDiv.addClass('HighlightRow'); 
} 

In the selector #parentDiv div.childClass, can you guarantee that div will be a direct descendent of #parentDiv? In which case:

.closest('#parentDiv>div.childClass');

and

$('#parentDiv>div.childClass')

You already have parentDiv. I'm guessing this is a DOM object, so you may be able to do the following:

$(parentDiv).children("div.childClass")

Just hide the DIV that is currently highlighted:

$('#parentDiv div.HighlightRow').removeClass("HighlightRow");