I have multiple inputs that each one has an increment and decrement button
The buttons will be pressed multiple times so I am looking to optimize my selector:
So should I keep the first one (which selects by attribute) or the second? Or anything more optimized.
$("[data-id-col="+thisID+"]")
$("input:tel#"+thisID+")
$("body").on('click','.incButton',e=>{
let thisID = e.currentTarget.getAttribute("d-id");
let colInput = $("[data-id-col="+thisID+"]");
colInput.val( parseInt( colInput.val())+1);
colInput.change();
});
HTML:
Input
<div class="handle-counter" id="handleCounter3">
<input type="tel" data-id-col="8900" id="qty_inputCol" class="qty_col">
</div>
Button
<button type="button" d-id="8888" class="btn btn-primary btn-block inc"></button>
-
2\$\begingroup\$ Unless you see this code taking a noticeable amount of time in devtools profiler, there's no need to optimize it. What you're doing now is premature optimization, which is pointless. If you really insist you can simply remember the element reference as an expando property on the clicked element. \$\endgroup\$woxxom– woxxom2019年10月30日 05:47:30 +00:00Commented Oct 30, 2019 at 5:47
1 Answer 1
Your second selector doesn't work with the data provided input:tel#8888
is not the id=
of the input.
IDs should start with a letter (for compatibility), so if you changed your input to <input id="inp8888">
then you could use input:tel#inp8888
in which case, you can use $("#inp8888")
as long as your IDs are unique (which they should be).
Selecting by ID is the fastest selection method.
jQuery uses document.getElementById(), which is faster
https://learn.jquery.com/performance/optimize-selectors/#id-based-selectors