-2

JQuery selector starting with # indicates an ID selection. There can always be only one element with the given ID. Somehow, JQuery was implemented to always return an array from the calls like $("#elemID").

To change the value of an element now, I have to write like:

$("#elemID")[0].value = "something";

Is there a different method to do this without referring an array index like:

$.getElem("elemID").value = "something";
T J
  • 42,762
  • 13
  • 83
  • 138
DPRao
  • 47
  • 7
  • 1
    With jQuery, if it is a form element: `$('#elem').val('value');`. Else `$('#elem').text('value')`. See http://api.jquery.com/val/ and http://api.jquery.com/text/ respectively. – kosmos Feb 04 '16 at 19:54
  • Generally it's bad practice to have more than one object with the same value in the ID tag. After all, what good is an **identifier** if it doesn't uniquely identify a specific object? – Jrud Feb 04 '16 at 19:57
  • Difference between `.val()` and `.text()` http://stackoverflow.com/a/807908/3648578 – kosmos Feb 04 '16 at 20:01
  • Thanks Kosmos! It works. But it always returns an array and sets the first objects value/text. I am good using it because i need not put array format in the code. – DPRao Feb 04 '16 at 20:07
  • *" There can always be only one element with the given ID"* - this is not true. There can be many such elements at a time in DOM. browser doesn't present you from doing so. It's just invalid markup. `invalid!=impossible` – T J Feb 05 '16 at 08:06

1 Answers1

2

jQuery selectors always return an array, even if that array is only one actual HTML element. Well, not really an array, it's a jQuery wrapper object, but it acts like an array.

If you want to set the value of an HTML object, use .val():

$('#elem').val('value');