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
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.
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 .
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.
val() for input or textarea elements. o . html() for value of a script element. Picking up html content from .
.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()
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With