I had an argument with a colleague of mine about element selection in jQuery.
Here is an example code:
$(function(){
$("body").on("submit", "#myForm", function(e){
e.preventDefault();
// here which selector would be quicker?
var randomVar = $(this).find("#myText").val(); // this one
var randomVar2 = $("#myText").val(); // or this one
console.log(randomVar);
console.log(randomVar2);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div>imagine this div has a lot of content and the HTML file is about 400 lines with many elements</div>
<form id="myForm">
<input type="text" id="myText" />
<input type="text" id="myText2" />
<input type="submit" />
</form>
</body>
He stated that using $(this).find("#id")
would be quicker as it only searches within the <form>
tag for the id. I was not sure exactly if that would be faster, assuming that the normal select by id $("#id")
works with O(1) complexity as a dictionary get key would work.
I tried reading through jQuery's docs about both selectors, but did not find any time complexities or anything that points to how fast those 2 perform. So my question is which selector would be better and quicker to use $(this).find("#id")
or $("#id")
? Thank you in advance for your help!