$(“#id”).val() : No find
$(“input[id=‘id’]”).val() : OK
Do you know the difference between the above two situations? Why would you do that?
$(“#id”).val() : No find
$(“input[id=‘id’]”).val() : OK
Do you know the difference between the above two situations? Why would you do that?
To answer this question, we need to understand how Jquery selectors work.
$("#id")
Internally uses document.getElementById();
$("input[id='id']")
Internally uses document.getElementsByTagName()
to get all the matching 'Element tag' and filters with id.
The main difference between both operations is case 1 returns only the matching object, but case 2 returns along with prevObj or the containing object.
Hence technically both operation with val()
should return the same result.
Are you asking why:
$(“#id”).val() // <--- This doesn't work,
// and
$(“input[id=‘id’]”).val() // <--- ... and this does work?
Assuming your markup looks something like this:
<label for="id"> Input </label> <br />
<input id="id" type="text" value="test"/>
... If this is the case, then the following should work (I've included vanilla JS Comparisons for reference, which is pretty close to how jQuery works under the hood anyway).
// The jQuery Way
const firstCase = $("#id").val() // "test"
const secondCase = $("input[id='id']").val() // "test"
// The Vanilla Way
const thirdCase = document.getElementById("id").value; // "test"
const fourthCase = document.querySelector("input[id='id']").value; // "test"
Please provide the HTML Markup you are trying to interact with, then we will get a better understanding of the problem you are trying to solve.