Bryan
Bryan

Reputation: 3009

Searching the DOM on click events

Say I have the following code:

$('.some-class a').click(function() {
    // Do something
});

Will JQuery search the DOM each time .some-class a is clicked? Or will the DOM be searched just once? I'm wondering if it will improve performance if I make $('.some-class a') a variable and change it to:

var $someClass = $('.some-class a');
$someClass.click(function() {
    // Do something
});

Upvotes: 1

Views: 110

Answers (3)

JorgeGarza
JorgeGarza

Reputation: 410

If you are to worried about the performance, maybe you can do it with native JS

[].forEach.call(document.querySelectorAll('.some-class a'), function (element) {
  element.addEventListener('click', function() {
      alert('clicked');
  }, false);
});

Just need to be aware that queryselectorall is not supported by IE8 http://caniuse.com/#search=queryselectorall

Upvotes: 0

Jeremy Thille
Jeremy Thille

Reputation: 26370

In this case :

$('.some-class a').click(function() {
    // Do something
});

This instruction will be executed once : jQuery will search the DOM once, find requested elements and attach click events to them. The end.

In this case :

function hideStuff(){
    $('.some-class a').hide()
}

jQuery will have to search the DOM every time the function is called. In order to avoid that, store the objects in a variable (it's called caching) :

var $elems = $('.some-class a')

function hideStuff(){
    $elems.hide()
}

Every time the hideStuff() function is called, jQuery won't have to search the DOM, it's already got all the elements stored in memory, so it's much faster.

Upvotes: 2

john Smith
john Smith

Reputation: 17906

it will bind the event to the selector once

if you want it for example to search for anchor everytime u click u could do :

 $('.some-class').on('click','a',function(){  /**/  });

Upvotes: 0

Related Questions