0

Is there any reason to use for ex. input#id? Why not just #id? Code below:

$("button").on("click", function() {
    var rate = $("#rate_1").val();
    var quant = $("#quant_1").val();
});

VS

$("button").on("click", function() {
    var rate = $("input#rate_1").val();
    var quant = $("input#quant_1").val();
});

HTML

<tr>
    <td><input type="textbox" id="quant_1" class="txtbox"></input></td>
    <td><input type="textbox" id="rate_1" class="txtbox"></input></td>
</tr>
Moo Kate
  • 37
  • 3
  • `input#id` will make the engine to first get only specific type of elements and the fetch element with necessary ID. This reduces lot of work for engine. – Rajesh Mar 16 '17 at 09:31
  • They are the same since you are specifying an `id` it does not matter how do you access it, I think `id` alone could be more readable. – Ahmad Mar 16 '17 at 09:32
  • @Rajesh I don't think there's an enormous impact on the engine since it's an id and there's only one element of it in the whole document, so it is already fast. – Ahmad Mar 16 '17 at 09:34
  • @Rajesh, that was my guess, but i wasn't sure :) – Moo Kate Mar 16 '17 at 09:35
  • @Ahmad How does engine fetch element with id? – Rajesh Mar 16 '17 at 09:35
  • @Ahmad but if there is a looooot of code there is propably a difference I guess. Anyway, even if it have marginal impact, it propably is good practice :) – Moo Kate Mar 16 '17 at 09:38
  • @Rajesh merely the whole document can only have one `id` so if you do `input#id` or `#id` is the same. – Ahmad Mar 16 '17 at 09:38
  • 1
    @Ahmad thank a lot for answers :) – Moo Kate Mar 16 '17 at 09:39

1 Answers1

1

In terms of the practical effect in this instance, there is no difference.

In terms of potential practical effect, input#id only selects elements that (a) are input elements and (b) have the id attribute set to id. #id only asks for the second check. So you are being slightly more specific. That said, if you have an id that could apply to multiple types of elements, you're doing something wrong.

In terms of performance effect, there is a slight difference. Behind the scenes, #id is found using document.getElementById (source). input#id uses jQuery.find and therefore ultimately document.querySelectorAll (source). The getElementById method will have marginally better performance -- but don't pay any attention to this. The gain will be so minuscule that you wouldn't notice it if it were repeated a thousand times.

The most significant difference: input#id is more characters to type and there is a larger chance of a typo.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318