1

In the HTML I have the following element:

HTML

<input id="userNameTxt" type="text" class="input" value='ABC>

And i am selecting it like this in jQuery:

APP.js

$(userNameTxt).val()

What is this selector selecting? (Like when I use $('.something') -> it's selecting the Class of the element or $('#something') it's selecting the ID.)

It seems to be selecting the ID, but then is it similar to the # selector? If so then when to use such selector?

Gaurav_soni
  • 6,064
  • 8
  • 32
  • 49
  • is there a variable declaration for userNameTxt in another part of your javascript? – theatlasroom Jan 31 '15 at 06:19
  • When you select with the id then it will return only one element, the first matched element in the DOM, but when you use class selector it will return all the DOM element. Since you can apply similar class to more than one element. So when you want to select for more than one element then apply same class to them and use class selector and when you want to retrieve one unique element then use id selector – Mukesh Agarwal Jan 31 '15 at 06:25
  • Your question doesn't tell us what the selector is. What's the value of `userNameTxt`? – Chris Martin Jan 31 '15 at 06:42
  • @ChrisMartin that is the question... OP doesn't have a variable called `userNameTxt` – Arun P Johny Jan 31 '15 at 06:43
  • @ArunPJohny The question asks how it's working; if there weren't a variable called `userNameTxt`, then it wouldn't be working. – Chris Martin Jan 31 '15 at 06:44
  • @ChrisMartin OP didn't create such a variable.... but as per the html spec the browser does... see the answer below – Arun P Johny Jan 31 '15 at 06:45
  • @ArunPJohny Agh, wow. Sorry, I've long forgotten about that "feature". – Chris Martin Jan 31 '15 at 06:47

1 Answers1

3

It is because the browser feature which will create global variables with element id properties.

If you use console.log(userNameTxt) you will be able to see the element get logged, so in your case you are passing a dom element reference to jQuery which is a valid param.

console.log(userNameTxt);
console.log(somename);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="userNameTxt" type="text" class="input" value='ABC' />
<div id="somename"></div>
Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • Right I'm not creating anything like var userNameTxt = "#userNameTxt"; So question: if i have multiple element with same id (i know i should not have same ID's) will it automatically create a global array of the elements ? – Gaurav_soni Jan 31 '15 at 06:36
  • @Gaurav_soni ID of an element must be unique.... but it looks like at least in chrome it is creating an array - [Fiddle](http://jsfiddle.net/arunpjohny/xfmw275z/1/). – Arun P Johny Jan 31 '15 at 06:41