Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding a JQuery complex chaining code example

I want to understand the meaning of the $ sign when added to the beginning of a variable and why we have to wrap the item variable with the $ sign ? in order to change a text value.

For this line of code:

var $item = $(item);

I think that $item is like any other variable ?

I have this short JQuery code:

var items = $('#special-features li');

items.width('50%')
    .height('200px')
    .addClass('hightlight bordered')
    .each(function(index, item){
        var $item = $(item);
        $item.text($item.text() + ' ' +
           $item.attr('data-features-id'));

});

Here is the result of the code above

enter image description here

like image 623
HDJEMAI Avatar asked Jun 27 '26 00:06

HDJEMAI


1 Answers

The code is just caching the $(item) object. As it is used multiple times it's better practice to cache the object instead of referencing from DOM which will improve the performance slightly.

var $item = $(item);
$item.text($item.text() + ' ' +
   $item.attr('data-features-id'));

The $ in $item is just a variable name. It is common practice to use $ at the beginning of variable that contains jQuery object.

like image 112
Tushar Avatar answered Jun 29 '26 13:06

Tushar