faster DOM traversals with jQuery

date: 8/7/12 tags: jquery javascript

One way to improve performance when traversing the DOM (besides searching for an ID instead of a class) is to save the HTML element as a javascript variable. Then use the jQuery find method to search the variable. So instead of traversing the entire DOM you are only searching through the variable you already set. This is especially helpful if you are going to perform multiple traversals on a specific section of HTML.

HTML:

<div id="container">
    <div id="header">header</div>
    <div id="content">
        <div id="stuff">stuff</div>
    </div>
    <div id="footer">footer</div>
</div>

javascript/jQuery:

//document ready
$(function(){
    //set variable
    var htmlElem = $('#content');

    //traverse and manipulate
    $(htmlElem).find('#stuff').addClass('active');
});
blog comments powered by Disqus