How to Use .html () in jquery (),. text () and. val () is used to read and modify the html structure of an element, the text content of an element, and the value of a form element. This section describes how to use .html () in jquery (),. text () and. val () is used to read and modify the html structure of an element, the text content of an element, and the value of a form element. JQuery provides multiple methods for you to operate on the HTML structure of an element and the text content of an element. For example, you can perform operations on the internal and surrounding elements of an existing element, add new elements before or after the element, or replace another element with one element. You can also read or modify the content or structure of an element. Sometimes we will be fuzzy. We don't know whether to add content to an element or add an element. For example, we need to effectively add content to an existing element.
Here we will share with you how to add, delete, and replace elements. jQuery provides three methods for us to operate on the element structure and content:
- . Html (): Read and modify the HTML content of a element, details. html ();
- . Text (): Read and modify the text content of an element, details. text ();
- . Val (): Read and modify the value field value of a form element. Details: val ().
As you will see, these methods allow you to easily read or modify the original content of an element or read and modify any HTML value, you can also easily read or modify the value Field Values in the form.
HTML structure of operating element --.html ()
The .html () method in jqueryallows you to read and modify the Html content of an element. There are three main usage methods: .html(,.html(htmlstring#,.html (function (index, html ){...}), next, let's take a look at their specific usage methods.
1. Read a simple HTML structure --.html ()
Syntax:
$("Element").html();
Return Value:String
Note:
The. html () method is used to obtain the HTML content of any element. If the selector selects more than one element at the same time, it can only read the HTML content of the first element. In addition, this method is invalid for XML files.
Parse () reads the HTML content of this element, for example:
HTML Code:
The Code is as follows:
This is a paragraph element, which contains a link element W3CPLUS
JQuery Code
The Code is as follows:
$ (Document). ready (function (){
Alert ("the html structure of the p element in Div. demo:" + $ ("p. demo p" ).html ());
});
Result
The above code will pop up a warning box that displays the elements in the original HTML Tag, as shown in. In the above example, the p. demo has only one P element. What if there are multiple p elements? What will happen? Let's take a look at it:
HTML Markup
The Code is as follows:
I am the first p element in P. demo: I am in the first P.
This is a paragraph element, which contains a link element W3CPLUS
JQuery Code
The Code is as follows:
$ (Document). ready (function (){
Alert ("the html structure of the p element in Div. demo:" + $ ("p. demo p" ).html ());
});
Effect
We can see from the above that the same jQuery code has different effects. This proves againIf you call the. HTML () method of multiple elements, the first element is read. In other words, if the selector matches more than one element, only the HTML content of the First Matching Element is obtained.
2XX modify the HTML content of a element --.html (htmlString)
Syntax:
$ ("Element" ).html (htmlString); // htmlString is an HTML string used to set each matching Element.
Return Value:JQuery object
Note:
Reset the html content of the First Matching Element. Any content of these elements is completely replaced by the new content. Based on the above example, the HTML content of the original paragraph is completely replaced:
HTML Markup
The Code is as follows:
I am the first p element in P. demo: I am in the first P.
This is a paragraph element, which contains a link element W3CPLUS
JQuery Code:
The Code is as follows:
$ (Document). ready (function (){
$ ("P. demo p" ).html ('Add a new title
I am the first p element in P. demo: I am in the first P.
');
});
Effect:
We learned from the above results that the "htmlString" structure specified in the evaluate (htmlString) method. "HtmlString" in the evaluate (htmlString) method is replaced. As shown in.
3. Use a callback function to replace the HTML content of an element.
Syntax:
$("Element").html(function(index,html){...});
Return Value:JQuery object
Note:
Returns a function for setting HTML content. The index location of the received element and the old HTML of the element are used as parameters.
When a callback function is used to replace the HTML content of an element, the following two conditions must be met:
- Position of the index value of the current element (the index value starts from 0 );
- The old html content of the current element.
The Return Value of the function is subsequently used as an alternative to HTML. This method is very convenient. If you want to replace the content of multiple elements, and you don't want to replace them with the same content, but with different content, then we can use this method to replace multiple elements with different html content based on their location or existing content (or both. Let's look at an example:
HTML Markup
The Code is as follows:
In the first P
W3CPLUS
JQuery Code:
The Code is as follows:
$ (Document). ready (function (){
$ ("P. demo p" functions .html (function (index, oldHtml ){
Return "I Am a paragraph" + (index + 1) + ":" + oldHtml;
});
});
Effect:
The plain text content of the Operation element --. text ()
The preceding .html () method allows you to read or modify the HTML content of an element, including the HTML tag of the element. The. text () method in jQuery is only an operation on the plain text of the element. Like the .html () method, he has three usage methods:
1. Read text content --. text ()
Syntax:
$("Element").text();
Return Value:Returns a string;
Note:
Combine the text content of each element in the Element Set, including its descendants .. The text(watermark and .html () methods are different. The. text () method can be used in XML and HTML documents .. The text () method is composed of all the text content contained in the matching element (because different browsers have different HTML analyzer, the line feed in the returned text may be different from other spaces .)
The use of the .text()and .html () methods are almost the same, such:
HTML Markup
The Code is as follows:
W3CPLUS
JQuery Code:
The Code is as follows:
$ (Document). ready (function (){
Content read by alert (". text ():" + $ ("p. demo p"). text ());
});
Effect:
We learned from the above results: Use. in the text () method, we only read the plain text content of an element, including its descendant elements, and the HTML tags (including the HTML tags of its descendant elements) in this element are stripped out, only text content is left.
The. text()and. html () methods can select multiple elements at the same time, but there is a difference :. when html () matches multiple elements, only the first matching element is read. the text () method is different. When matching multiple elements, the text will read the content of multiple elements at the same time, for example:
HTML Markup
The Code is as follows:
W3CPLUS
Section 2: W3CPLUS
JQuery Code
The Code is as follows:
$ (Document). ready (function (){
Alert (". text () method:" + $ ("p. demo p"). text ());
Alert (". html () method:" + $ ("p. demo p" ).html ());
});
Effect:
2. Replace text content --. text (textString)
Syntax
$ ("Element"). text (textString); // textString is used to set the text that matches the Element content.
Return Value:JQuery object
Note:
The .text(textstring## and .html (htmlString) methods are the same to replace the content of elements. The differences between them are:.The html (htmlString) method replaces the original content with the HTML tag as a new HTML Tag. text (textString) converts HTML tags into plain text content to replace the old content of the element. In other words, if the. text (textString) method contains HTML tags, this method replaces <with <,> with>. In front of the .html(htmlstringdomaindetail, we can basically replace .html () with. text ().
HTML Markup
The Code is as follows:
W3CPLUS
Section 2: W3CPLUS
JQuery Code
The Code is as follows:
$ (Document). ready (function (){
$ ("P. demo p"). text ('add New title
I am the first p element in P. demo: ');
});
Effect:
Evaluate (htmlString) for comparison. However, they have the following similarities:If multiple elements are matched, using. text (textString) will replace the content of the matched element with the same content.
3. Use a callback function to replace the text content of an element.
Like the .text() and .html () methods, the content of multiple elements must be dynamically replaced by a callback function, instead of replacing multiple elements with the same content like. text (textString.
Syntax
$("Element").text(function(index,text){...});
Return Value:JQuery
Note:
Returns a function used to set text content. The index location of the received element and the old text value of the element are used as parameters. To use a callback function to replace the content of an element, the following two conditions must be met:
- Position of the index value of the current element (the index value starts from 0 );
- The old text content of the current element.
The Return Value of the function is then used as the plain text content of the substitution element. This method is very convenient. If you want to replace the content of multiple elements, and you don't want to replace them with the same content, but with different content, then we can use this method to replace multiple elements with different thousands of texts based on their locations or existing content (or both. Let's look at an example:
HTML Markup
The Code is as follows:
In the first P
W3CPLUS
JQuery Code:
The Code is as follows:
$ (Document). ready (function (){
$ ("P. demo p"). text (function (index, oldText ){
Return (index + 1) + "." + oldText;
});
});
Effect
Operation form field Value --. val ()
The .html () and. text () introduced earlier cannot be operated on the input element, so let's look at a. val () method. This method is like the. text () method. You can read and modify the value of the form field "value.
1. Get the form Element value --. val ()
Syntax
$("Element").val();
Return Value:Returns a string or array.
Description
The. val () method is mainly used to obtain the values of form elements. For"The. val () method returns an array containing each selected option."And check box, single-choice ([type =" checkbox "], [type =" radio "]) You can use the": selected "and": checked "selectors to obtain the value. Here are several examples:
HTML Markup
The Code is as follows:
Red
Yello
Blue
10 pt
12 pt
14 pt
JQuery Code
The Code is as follows:
$ (Document). ready (function (){
$ ('# SubmitBtn'). click (function (){
Alert ($ ('# colorRadio input: radio'). val ());
Alert ($ ('# sizeCheck input: checkbox'). val ());
});
});
Effect
. Val () returns the first matched element set. Sometimes you want to return the value of the selected radio or checkbox. the val () method returns the first value, as shown in figure. If you want to return the selected value, you need to perform the following operations to get the selected value:
The Code is as follows:
$ (Document). ready (function (){
$ ('# SubmitBtn'). click (function (){
Alert ($ ('input: radio [name = color]: checked'). val ());
Alert ($ ('input: checkbox [name = size]: checked'). val ());
});
});
At this time, the single-choice (radio) will return the value you selected, but the checkbox is not. If you select multiple checkboxes at the same time. val () Only returns the value in the first selection. If no value is selected, "undefined" is added ". As mentioned earlier, when multiple "checkbox" selections are selected, the return value will be the first value. If we need to return all the results, we need to use each () to traverse the checkbox.
The Code is as follows:
$ (Document). ready (function (){
$ ('# SubmitBtn'). click (function (){
Alert ($ ('input: radio [name = color]: checked'). val ());
$ ('Input: checkbox [name = size]: checked'). each (function (){
Alert ($ (this). val ());
});
});
});
In addition, val () can be divided into two situations during "select,
When the. val () method is applied inWhen the. val () method is applied toElement, an array containing each selected option is returned.Here is an example.
HTML Markup
The Code is as follows:
JQuery Code
The Code is as follows:
$ ("# GetSelectValue"). click (function (){
Alert ($ ("# dropdown"). val ());
Var colors = $ ("# listbox"). val ();
For (var key in colors ){
Alert (colors [key]);
}
});
2. Replace the Value value of the form element --. val (Value)
Syntax
$ ("Element"). val (value); // value indicates a text string or an array in the form of a string to set the value of each matching Element.
Return ValueJQuery object
Description
This method is often used to set the value of form fields."Element, multiple options can be selected through an array .. Val (value) can change the value of the selected element at the same time, and its value is the same, for example: The Code is as follows:$ ("Input"). val ("test "); The above code will eventually replace the value of all inupt values with "test", which is generally not used in normal applications .. Val (value) is often applied to the focus and blur of input [type = "text"], for example:HTML Markup The Code is as follows:
JQuery Code
The Code is as follows:
$ ("Input: text"). focus (function (){
Var $ inputTextVal = $ (this). val ();
If ($ inputTextVal = this. defaultValue ){
$ (This). val ("");
}
});
$ ("Input: text"). blur (function (){
Var $ inputTextVal = $ (this). val ();
If ($ inputTextVal = ""){
$ (This). val (this. defaultValue );
}
});
3. Use a callback function to replace the value of the form field "value ".
Previous. val (value) can change the value of the selected form element to the same value. Therefore, we usually need to set different values. In this case, we need to use this method, set this value using a function. This function uses two parameters: the value of the current element and its current value.
Syntax
$("Element").val(function(index,value){...});
Return ValueJQuery object
Description
Use the return value of this function to set the "value" value of each matching input element. Let's look at an instance on checkbox and radio:
HTML Markup
The Code is as follows:
JQuery Code
The Code is as follows:
$ (Document). ready (function (){
$ ("Input: radio [name = color]"). val (function (index, oldVal ){
Return "color-" + (index + 1) + ":" + oldVal;
});
$ ("Input: checkbox [name = size]"). val (function (index, oldVal ){
Return "size-" + (index + 1) + ":" + oldVal;
});
$ ("# SetValue"). click (function (){
Var $ msg = $ ("input: radio [name = color]: checked"). val () + ",";
$ ("Input: checkbox [name = size]: checked"). each (function (){
$ Msg + = $ (this). val () + ",";
});
$ ("# TxtBox"). val ($ msg );
});
});
For the multi-selection drop-down box, we can change it like this:
HTML Markup
The Code is as follows:
Red Yellow Blue
Red Yellow Blue
JQuery Cody
The Code is as follows:
$ (Document). ready (function (){
$ ('# Dropdown'). val ('yellow ');
$ ('# Listbox'). val (['red', 'blue']);
});
The specific usage of. val () is introduced above. Under what circumstances can we use the. val () method?
- You can use. val () to read and modifySelected items. As shown in the preceding example, these values are already in the list;You can use. val () to readIf you select multiple option values,. val () returns an option array, but you cannot use. val () to set multiple values for it;
- You can use. val () is used to read the values of radio and checkbox. You can also use the checked = "checked" attribute to read the selected values. However, you must use each () to traverse the checkbox, otherwise, only the first selected value can be read;
- You can use function to dynamically change the value of multiple elements in a form.
In this section, we need to learn how to use the .html (),. text () and. val () methods in jquery. finally, we will summarize these three methods:
- . Html ()Use HTML tags for reading and modifying elements
- . Text ()The plain text content used to read or modify elements.
- . Val ()Used to read or modify the value of a form element.
Functional Comparison of the three methods
- The three types of content .html (,.text(),.val()..) are used to read and select elements. Only the content .html () is used to read the HTML content of elements (including its Html tags ),. text () is used to read the plain text content of an element, including its child element ,. val () is the "value" value used to read form elements. Except () is the same. If it is applied to multiple elements, it can only read the "value" value of the first form element,. text () is different from them, if. when text () is applied to multiple elements, the text content of all selected elements is read.
- . Html (htmlString ),. text (textString) and. val (value) is used to replace the content of the selected element. If the three methods are applied to multiple elements at the same time, the content of all selected elements will be replaced.
- . Html (),. text (),. val () can use the return value of the callback function to dynamically change the content of multiple elements.