-3
$(“#id”).val() : No find
$(“input[id=‘id’]”).val() : OK

Do you know the difference between the above two situations? Why would you do that?

Maxime
  • 838
  • 6
  • 18
winry
  • 3
  • 3

2 Answers2

2

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.

Deepak A
  • 1,624
  • 1
  • 7
  • 16
RNV
  • 21
  • 3
  • But in reality, the first selector is not found and the second selector only gets the value. – winry Apr 12 '19 at 06:35
0

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.

Chris Talke
  • 120
  • 1
  • 8