K Split X
K Split X

Reputation: 4727

When do I use .val() vs .innerHTML?

In JQuery when trying to access elements, I see that if I have a form (lets say a textarea), and I want to get the text inside of it, I must use $("textarea").val();

Instead if I have a h1 element, I must use $("h")[0].innerHTML;

Why is this the case? h1.val()/textarea.innerHTML do not work

Upvotes: 15

Views: 26630

Answers (5)

You Old Fool
You Old Fool

Reputation: 22941

textarea.innerHTML actually will work to get the html content of the textarea as it's initially rendered, whereas val() will get the current value based on user input. val() as others have stated only works on form elements so it would have no result for an <h1>.

$('textarea').on('input', function() {
  $('#innerhtml').text(this.innerHTML);
  $('#val').text($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Type in the textarea below to see results:
<br>
<textarea>test123</textarea>
<div>textarea innerHTML:</div>
<div id="innerhtml"></div>
<div>textarea val:</div>
<div id="val"></div>

Upvotes: 1

Geert-Jan
Geert-Jan

Reputation: 18895

you could use h1.text() or h1.html() which map to innerText and innerHTML respectively.

As for val() that maps to input.value.

Using the jquery equivalents gives you cross-browser compatibility, although that's probably more of a historic relic. New browsers probably implement these features the same way.

As a general rule: value is used on input elements, innerHTML on non-input fields.

Upvotes: 0

Ionut Necula
Ionut Necula

Reputation: 11472

.val() is used to get/replace input elements values in jQuery, alternative in JS is .value.

innerHTML or jQuery's .html() is used to get/replace the whole markup inside an element, not input elements.

text() is used almost the same as JS innertHTML, only it gets/replaces the text inside an element, not all the tags etc. It's bassically the equivalent of JS innerText

Reference links about innerHTML, innerText, val(), text(), html()

Upvotes: 19

Ivan
Ivan

Reputation: 1

.val() is used to get value from input elements in jQuery. Alternative in JavaScript is .value.

.innerHTML is used to put some value between some tags. So innerHTML is a DOM property to insert content to a specified id of an element, and with .val() you just get value from some input tags.

Upvotes: -1

mojtaba zangeneh
mojtaba zangeneh

Reputation: 141

Because all the inputs in Html have val() and they can send their values to be processed by a form, such as textarea, text, submit, ...

but tags like h1, span, ... dont participate in form and wont be processed, and also they may have inner tags and html as well.

Upvotes: 0

Related Questions