Search code examples
jqueryperformancejquery-selectorschaining

Does chaining jQuery selectors have any negative effects?


Are there any negative implications to chaining jQuery API calls on a selector? Negative implications dealing with performance, design, susceptibility to memory leaks are what I'm particularly interested in.

So, would chaining a statement such as this:

$('.myElement').css('color','green')
               .attr('title','My Element')
               .click(function(){ console.log('clicked') });

Leave the application open to any of the aforementioned negative implications?

I personally don't have any problems with chaining jQuery expressions at all, but I've seen a lot of people bash chaining and I want to know if there is any concrete benefits of avoiding it, or if it's just a matter of readability and personal style.


Solution

  • Chaining is actually better than doing this:

    $('.myElement').css('color','green')
    $('.myElement').attr('title','My Element')
    $('.myElement').click(function(){ console.log('clicked') });
    

    Since doing so would make jquery 'jump into the pool' looking for my element 3 times, while if you chain your orders it will just look in the pool once (notice the pool is the DOM :)