Jquery method to obtain the content of html elements: 1. Use html() to return the content of the selected element, the syntax is "$(selector).html()"; 2. Use text() to return The text content of the selected element, the syntax is "$(selector).text()".
The operating environment of this tutorial: windows10 system, jquery1.8.3. This article is applicable to all brands of computers.
[Related recommendations: jQuery video tutorial]
1. html(): Returns the original HTML document, but there may be compatibility in IE properties, as follows
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <p id="box"> <p class="b2">我是一个p元素</p> <span>你好</span> </p> </body> <script src="libs/jquery-1.8.3.min.js"></script> <script type="text/javascript"> $(function(){ var str = $("#box").html(); console.log(str); // <p>我是一个p元素</p> // <span>你好</span> //解释:该方法使用的是JS中的innerHTML()有些浏览器返回的结果可能不是原始文档的 HTML 源代码。例如,如果属性值只包含字母数字字符,Internet Explorer有时丢弃包裹属性值的引号 }); </script> </html>
2, text():Get the value of each element in the matching element set Merge text, including their descendants
.text()
The method cannot be used on input elements or scripts elements, input
or textarea
You need to use the .val() method to get or set the text value .html()
method<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <p id="box"> <p class="b2">我是一个p元素</p> <span>你好</span> </p> </body> <script src="libs/jquery-1.8.3.min.js"></script> <script type="text/javascript"> $(function(){ var str = $("#box").text(); console.log(str); // 我是一个p元素 // 你好 });</script> </html>
3. val() method
This method is mostly used for input elements.
For more programming-related knowledge, please visit: Programming Courses! !
The above is the detailed content of How to get the content of html element with jquery?. For more information, please follow other related articles on the PHP Chinese website!