What is advantage to use var with id?


var mything = $('#mything').val(); // Is get the value for later

But I saw sometimes have set a var just for an id

var mything = $('#mything');

	mything.on('mouseenter', function() {
		$('#text').css('font-weight', '700');

	$('#mything').on('mouseenter', function() {
		$('#text').css('font-weight', '700');

What is the purpose to set a var just for an id? Is mean something like on count scripts?


$() is a function, that traverses DOM tree to find queried element(s). When you do var mything = $('#mything'); you’re invoking this function once and saving result to a variable, otherwise you’re invoking it over and over.

Traversing DOM is generally considered to be an expensive operation. (Of course not as expensive as keeping jQuery in scope :wink: )

1 Like