Overview and usage of jquery).html (),. text () and. val ()

Source: Internet
Author: User

This section describes how to use the following methods in jquery: .html (),. text (), and. val () 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:

  1. . Html (): Read and modify the HTML content of a element, details. html ();
  2. . Text (): Read and modify the text content of an element, details. text ();
  3. . 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:

Copy codeThe Code is as follows: <div class = "demo">
<P> This is a paragraph element that contains a link element <a href = "#"> W3CPLUS </a> </p>
</Div>

JQuery Code Copy codeThe Code is as follows: $ (document). ready (function (){
Alert ("the html structure of the p element in Div. demo:" + $ ("div. 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. The above is div. demo with only one P element. What if there are multiple? What will happen? Let's take a look at it:

HTML Markup

Copy codeThe Code is as follows: <div class = "demo">
<P> I am the first P element in div. demo: <a href = "#"> I am in the first P </a> </p>
<P> This is a paragraph element that contains a link element <a href = "#"> W3CPLUS </a> </p>
</Div>

JQuery Code
Copy codeThe Code is as follows: $ (document). ready (function (){
Alert ("the html structure of the p element in Div. demo:" + $ ("div. 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

Copy codeThe Code is as follows: <div class = "demo">
<P> I am the first P element in div. demo: <a href = "#"> I am in the first P </a> </p>
<P> This is a paragraph element that contains a link element <a href = "#"> W3CPLUS </a> </p>
</Div>

JQuery Code:
Copy codeThe Code is as follows: $ (document). ready (function (){
$ ("Div. demo p "demo.html ('

});

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:

  1. Position of the index value of the current element (the index value starts from 0 );
  2. 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

Copy codeThe Code is as follows: <div class = "demo">
<P> <a href = "#"> I am in the first P </a> </p>
<P> <a href = "#"> W3CPLUS </a> </p>
</Div>

JQuery Code:
Copy codeThe Code is as follows: $ (document). ready (function (){
$ ("Div. 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

Copy codeThe Code is as follows: <div class = "demo">
<P> <a href = "#"> W3CPLUS </a> </p>
</Div>

JQuery Code:
Copy codeThe Code is as follows: $ (document). ready (function (){
Content read by alert (". text ():" + $ ("div. 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

Copy codeThe Code is as follows: <div class = "demo">
<P> <a href = "#"> W3CPLUS </a> </p>
<P> I am Section 2: <a href = "#"> W3CPLUS </a> </p>
</Div>

JQuery Code
Copy codeThe Code is as follows: $ (document). ready (function (){
Alert (". text () method:" + $ ("div. demo p"). text ());
Alert (". html () method:" + $ ("div. 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 & gt. In front of the .html(htmlstringdomaindetail, we can basically replace .html () with. text ().

HTML Markup

Copy codeThe Code is as follows: <div class = "demo">
<P> <a href = "#"> W3CPLUS </a> </p>
<P> I am Section 2: <a href = "#"> W3CPLUS </a> </p>
</Div>

JQuery Code
Copy codeThe Code is as follows: $ (document). ready (function (){
$ ("Div. demo p "). text ('

});

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:

  1. Position of the index value of the current element (the index value starts from 0 );
  2. 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

Copy codeThe Code is as follows: <div class = "demo">
<P> <a href = "#"> I am in the first P </a> </p>
<P> <a href = "#"> W3CPLUS </a> </p>
</Div>

JQuery Code:
Copy codeThe Code is as follows: $ (document). ready (function (){
$ ("Div. 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 "<select multiple =" multiple ">" element ,. the val () method returns an array containing each selected option. For the following selection box "<select>" 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

Copy codeThe Code is as follows: <div id = "colorRadio">
<Input type = "radio" name = "color" id = "rd1" value = "Red"/> Red
<Input type = "radio" name = "color" id = "rd2" value = "Yello"/> Yello
<Input type = "radio" name = "color" id = "rd3" value = "Blue"/> Blue
</Div>
<Div id = "sizeCheck">
<Input type = "checkbox" name = "size" id = "partition" value = "10 pt"/> 10 pt
<Input type = "checkbox" name = "size" id = "ch2" value = "12 pt"/> 12 pt
<Input type = "checkbox" name = "size" id = "ch3" value = "14 pt"/> 14 pt
</Div>
<Input type = "button" id = "submitBtn" value = "Get Value"/>

JQuery Code
Copy codeThe 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:

Copy codeThe 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.Copy codeThe 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. when the val () method is applied to the <select> element, the selected value is returned. when the val () method is applied to the <select multiple = "multiple"> element, an array containing each selected option is returned.Here is an example.

HTML Markup

Copy codeThe Code is as follows: <form action = "" method = "post">
<Select id = "dropdown">
<Option> Red </option>
<Option> Yellow </option>
<Option> Blue </option>
</Select>
<Select id = "listbox" multiple = "multiple">
<Option> Red </option>
<Option> Yellow </option>
<Option> Blue </option>
</Select>
<Input type = "button" id = "getSelectValue" value = "Get Value"/>
</Form>

JQuery Code
Copy codeThe 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 the form field. For the "<select multiple =" multiple ">" 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:

Copy codeThe 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

Copy codeThe Code is as follows: <input type = "text" id = "textBox" value = "Hello, jQuery! "/>

JQuery Code
Copy codeThe 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

Copy codeThe Code is as follows: <form action = "">
<Div id = "colorRadio">
<Input type = "radio" name = "color" id = "rd1" value = "Red"/> <span id = "color1"> Red </span>
<Input type = "radio" name = "color" id = "rd2" value = "Yellow"/> <span id = "color2"> Yellow </span>
<Input type = "radio" name = "color" id = "rd3" value = "Blue"/> <span id = "color3"> Blue </span>
</Div>
<Div id = "sizeCheck">
<Input type = "checkbox" name = "size" id = "regular" value = "10 pt"/> <span id = "size1"> 10 pt </span>
<Input type = "checkbox" name = "size" id = "ch2" value = "12 pt"/> <span id = "size2"> 12 pt </span>
<Input type = "checkbox" name = "size" id = "ch3" value = "14 pt"/> <span id = "size3"> 14 pt </span>
</Div>
<Input type = "text" id = "txtBox" disabled = "disabled"/>
<Input type = "button" id = "setValue" value = "Set Value"/>
</Form>

JQuery Code
Copy codeThe 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

Copy codeThe Code is as follows: <select id = "dropdown">
<Option> Red </option>
<Option> Yellow </option>
<Option> Blue </option>
</Select>
<Select id = "listbox" multiple = "multiple">
<Option> Red </option>
<Option> Yellow </option>
<Option> Blue </option>
</Select>

JQuery Cody
Copy codeThe 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?

  1. You can use. val () to read and modify the selected list items. As shown in the preceding example, these values are already in the list;
  2. You can use. val () to read <select multiple = "multiple"> selected value. If you select multiple options. val () returns an option array, but you cannot use it. val () sets multiple values for him;
  3. 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;
  4. 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:

  1. . Html ()Use HTML tags for reading and modifying elements
  2. . Text ()The plain text content used to read or modify elements.
  3. . Val ()Used to read or modify the value of a form element.

Functional Comparison of the three methods

  1. 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.
  2. . 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.
  3. . Html (),. text (),. val () can use the return value of the callback function to dynamically change the content of multiple elements.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.