This article brings you what is the difference between text(), html() and val() in JQuery? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Definition and usage
text() method method sets or returns the text content of the selected element
The code is as follows
nbsp;html> <meta> <meta> <meta> <script></script> <title>Document</title> <div>div有文本内容</div> <div> div2内的文本 <span>span内有文本内容</span> </div> <input> <input> <button></button> <script> console.log($("#div1").text()); console.log($("#div2").text()); console.log($("#div2 span").text()) ; console.log($("#input1").text()); console.log($("#input2").text()); console.log($("#button1").text()); </script>
console print Results
It can be seen that text() only outputs the text content within the label, which is the same as the innerText method of js
Definition and usage
html( ) method returns or sets the content (inner HTML) of the selected element, including tags.
If this method does not set parameters, it returns the current content of the selected element.
<div>div有文本内容</div> <div> div2内的文本 <span>span内有文本内容</span> </div> <input> <input> <button></button> <script> console.log($("#div1").html()); console.log($("#div2").html()); console.log($("#div2 span").html()); console.log($("#input1").html()); console.log($("#input2").html()); console.log($("#button1").html()); </script>
The result of printing through the console
Print the text content in the current tag. If there is a sub-tag, combine the sub-tag itself and the Print the text together
This is similar to innerHTML of js
Definition and usage
The val() method returns or sets the value of the selected element.
The value of the element is set through the value attribute. This method is mostly used for input elements.
Method is mainly used to obtain the value of form elements
If this method does not set parameters, it returns the current value of the selected element.
<div>div有文本内容</div> <div> div2内的文本 <span>span内有文本内容</span> </div> <input> <input> <button></button> <script> console.log($("#div1").val()); console.log($("#div2").val()); console.log($("#div2 span").val()); console.log($("#input1").val()); console.log($("#input2").val()); console.log($("#button1").val()); </script>
Printing the results through the console
val() is used to output the data in the form. It can be seen that the text in the p and span tags are not the same. It was not output. I also tested the H5 new tag placeholder
and it was also not output, so this val should only be for the value attribute of the tag
This article is all here It’s over. For more other exciting content, you can pay attention to the jquery video tutorial column on the PHP Chinese website!
The above is the detailed content of What are the differences between text(), html() and val() in JQuery?. For more information, please follow other related articles on the PHP Chinese website!