HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

jQuery duplicated selector

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
duplicatedjqueryselector

Problem

$("#colors_added").html(parseFloat($("#colors_added").html()) + 1);


This JS line makes my IDE go Duplicated jQuery selector with the following explanation:


Checks that jQuery selectors are used in an efficient way. It suggests to split descendant selectors which are prefaced with ID selector and warns about duplicated selectors which could be cached.

I've made a screenshot of it:

Is my IDE on to something here, can I write this in a better way?

Solution

You should cache your selector in a variable:

var $addedColors = $("#colors_added");
$addedColors.html(parseFloat($addedColors.html()) + 1);


Reason: placing selectors in variables is recommended, since overusing selectors can result in poor performance.

Everytime you would call a function on $("#colors_added"), the whole DOM has to be parsed by the browser. This is not the case when you store it in a variable.

Also, it's a general principle to not repeat yourself in code, also called the DRY principle (as mentioned by Peter Rader in the comments).

Code Snippets

var $addedColors = $("#colors_added");
$addedColors.html(parseFloat($addedColors.html()) + 1);

Context

StackExchange Code Review Q#70298, answer score: 13

Revisions (0)

No revisions yet.