Home > Article > Web Front-end > How to modify the content of a node in jquery
Jquery method to modify node content: 1. Use text() to modify the text content of the node, the syntax is "node object.text("new text content")"; 2. Use html() to modify the node content. Directly rewrite the content of the node, the syntax is "node object.html("new node content")".
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
jquery modifies the content of the node
Method 1: Use text()
text( ) method sets or returns the text content of the selected element.
When this method is used to return content, the text content of all matching elements is returned (HTML tags will be removed).
When this method is used to set content, the content of all matching elements is rewritten.
Example:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-1.10.2.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { $("p").text("Hello world!"); }); }); </script> </head> <body> <button>修改所有p元素的文本内容</button> <p>这是一个段落。</p> <p>这是另一个段落。</p> </body> </html>
Method 2: Using html()
html () method sets or returns the content of the selected element (innerHTML).
When this method is used to return content, the content of the first matching element is returned.
When this method is used to set content, the content of all matching elements is rewritten.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-1.10.2.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { $("p").html("Hello <b>world!</b>"); }); }); </script> </head> <body> <button>修改所有P元素的内容</button> <p>这是一个段落。</p> <p>这是另一个段落。</p> </body> </html>
Extended knowledge: Comparison of html() and text()
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <script src="js/jquery-1.10.2.min.js"></script> <script> $(function () { var strHtml = $("p").html(); var strText = $("p").text(); $("#txt1").val(strHtml); $("#txt2").val(strText); }) </script> </head> <body> <p><strong style="color:hotpink">PHP中文网</strong></p> html()是:<input id="txt1" type="text" /><br /> text()是:<input id="txt2" type="text" /> </body> </html>
As can be seen from this example, html() obtains all the content inside the element, while text() obtains only the text content.
The difference between the two methods html() and text() can be clearly compared from the following table.
HTML code | html() | text() |
---|---|---|
PHP Chinese website | PHP Chinese website | |
##PHP中文网 | PHP中文网 | |
(empty string) |
The above is the detailed content of How to modify the content of a node in jquery. For more information, please follow other related articles on the PHP Chinese website!