Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 356
K Split X Avatar asked Dec 27 '16 20:12

K Split X


People also ask

What is the difference between innerHTML and value?

value gives you the currently-set value of a form element (input, select, textarea), whereas . innerHTML builds an HTML string based on the DOM nodes the element contains.

Why you shouldn't use innerHTML?

The use of innerHTML creates a potential security risk for your website. Malicious users can use cross-site scripting (XSS) to add malicious client-side scripts that steal private user information stored in session cookies. You can read the MDN documentation on innerHTML .

What does VAL () do in Javascript?

The val() method returns or sets the value attribute of the selected elements. When used to return value: This method returns the value of the value attribute of the FIRST matched element.

What is difference between Val and HTML in jquery?

val() for input or textarea elements. o . html() for value of a script element. Picking up html content from .


2 Answers

.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()

like image 157
Ionut Avatar answered Sep 21 '22 15:09

Ionut


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>
like image 30
Eaten by a Grue Avatar answered Sep 17 '22 15:09

Eaten by a Grue