38

If I have a textarea like var textarea = $('textarea'), how can I set the value to it using the JavaScript property value, and not the jQuery property val()?

I think I need to convert textarea to a JavaScript object first, but how do I?

double-beep
  • 5,031
  • 17
  • 33
  • 41
Alex
  • 66,732
  • 177
  • 439
  • 641
  • 1
    Worth pointing out that while what you're talking about is in fact a 'javascript' object, more specifically and usefully it's really a property of a 'Node' object. These are created by browsers, are (mostly) similar between them, and they are normalized and added on to by jQuery. The same Node object lives deep within the jQuery object still though (with some properties reset/normalized by jQuery) – Alex Mcp Apr 04 '11 at 01:38

5 Answers5

71

You can use the dereferencing operator, or the .get() method to "Retrieve the DOM elements matched by the jQuery object."

Examples:

txtArea[0].value = "something";

or:

txtArea.get(0).value = "something";
karim79
  • 339,989
  • 67
  • 413
  • 406
15

The jQuery .get() will do that for you

http://api.jquery.com/get/

Quoted:

Without a parameter, .get() returns all of the elements:

alert($('li').get());

With an index specified, .get() will retrieve a single element:

($('li').get(0));

...we can use the array dereferencing operator to get at the list item instead:

alert($('li')[0]);
Community
  • 1
  • 1
nonopolarity
  • 146,324
  • 131
  • 460
  • 740
9

jQuery objects are Javascript objects.

You're trying to learn about the world of pain known as raw DOM scripting.

You can write

document.getElementsByTagName("textarea")[0].value = whatever;

This will get the first <textarea> and set its value.
If you want to set values for all of them, you'll need a loop.

You can also get a raw DOM element out of a jQuery object by writing $(whatever)[0].

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
6

You can pull the HTMLElement using array notation:

$('textarea')[0].value

...will get the value of the first element in the $('textarea') jQuery list.

mVChr
  • 49,587
  • 11
  • 107
  • 104
0

We can use javascript's querySelector() function to get a standard javascript DOM object.

Example :

<ul id="category"><li><label><input data-id="1" data-label="CBSE" data-filterClass="category" name="category" type="checkbox"> CBSE </label></li>
console.log(document.querySelector('input[data-id="1"]'));

You will get javascript DOM object for given selector.

YakovL
  • 7,557
  • 12
  • 62
  • 102
  • Although this sounds good for the example case, you should probably add something about how much jQuery selectors does `querySelector` support. Not all of them, right? – YakovL Jul 26 '16 at 18:55