Home >
Article > Web Front-end > How to change the content of
Two modification methods: 1. Use the jquery selector to obtain the h tag object, and use text() to modify the text content of the object. The syntax is "$("selector").text("new content") ;"; 2. Use the jquery selector to obtain the h tag object, and use html() to modify the content of the object (the content of the text and HTML tag), with the syntax "$("selector").html("new content"); ".
The operating environment of this tutorial: windows7 system, jquery3.6.1 version, Dell G3 computer.
Two ways to change the content of the
Method 1: Use text() to change the text content
text() can set the text content of the element, which can be changed by simply setting the text content to a new value.
Modification steps:
Use jquery selector to obtain the h tag (h1~h6) object
$("选择器")
Use text() to modify the content of the obtained object
对象.text("新内容")
Example:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-3.6.1.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { $("h1,h2,h3,h4").text("修改后的新文本内容"); }); }); </script> </head> <body> <button>改变所有h元素的文本内容</button> <h1>这是一个大标题。</h1> <h2>这是另一个标题。</h2> <h3>这是另一个标题。</h3> <h4>这是另一个段落。</h4> </body> </html>
Method 2: Use html() changes tag content
html() can set or return content that contains text and HTML tags.
Modification steps:
Use jquery selector to obtain the h tag (h1~h6) object
$("选择器")
Use html() to modify the content of the obtained object
对象.html("新内容")
Example:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-3.6.1.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { $("h1").html("修改后的新文本内容"); $("h2,h3,h4").html('<span style="color: red;">修改后的新文本内容</span>'); }); }); </script> </head> <body> <button>改变所有h元素的文本内容</button> <h1>这是一个大标题。</h1> <h2>这是另一个标题。</h2> <h3>这是另一个标题。</h3> <h4>这是另一个段落。</h4> </body> </html>
Expand knowledge: html () Comparison with text()
html() obtains all the content inside the element, while text() obtains only the text content.
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <script src="js/jquery-3.6.1.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>
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 change the content of