Javascript – JQuery: How to cache DOM


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,  + 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");

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"); 

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




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


Just hide the DIV that is currently highlighted:

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