Last Updated: February 25, 2016
·
21.87K
· sir_ov

Save DOM elements in variables using jQuery

This is useful when you need to do different operations with the same DOM element like this:

$('li.current').removeClass('inactive');
$('li.current').data('active', 1);
$('li.current').addClass('active');

Of course we can bind functions like

$('li.current').removeClass('inactive').addClass('active').data('active',1);

But if we need a validation or use it to do another operations the best thing that we can do is:

var $li_current = $('li.current');

And with this we just need to call our variable li_current to work with the DOM element.

6 Responses
Add your response

Great post!

Personal preference, but I like to prefix my jQuery objects with a $ to offer quick reference that it is a jQuery object and not just another variable.

over 1 year ago ·

@stevenwadejr Thank you, you're right and I agree with you, thats a better way to know that you're treating with a jquery object

over 1 year ago ·

It´s just a variable assignement. It should be clear that $(<selection>) executes every time a new query on the DOM.

over 1 year ago ·

Typically, CamelCase javascript variables/functions/etc. Underscore Ruby variables/functions/etc. Hyphenate css class/id names.

over 1 year ago ·

@becreative-germany yes it's just a variable assignment, but for example if your selector has classes is more efficient to save it on a variable than search it in all the DOM every time you need it, i agree that if the element has an ID, the jQuery funcion use getElementById native JS function, so this should have no problems, but for classes is more efficient save it on a variable.

@itg you're right, thank you for the observation!

over 1 year ago ·

Thanks, wasn't sure how to do this so this helped a lot!

over 1 year ago ·