Home > Web Front-end > JS Tutorial > How to get the content of html element with jquery?

How to get the content of html element with jquery?

青灯夜游
Release: 2020-11-30 14:15:34
Original
5407 people have browsed it

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()".

How to get the content of html element with jquery?

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

  • Principle: Use innerHTML()
<!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>
Copy after login

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
  • To get the value of the scripts element, use the .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>
Copy after login

3. val() method

  • #The value of the element is set through the value attribute.
  • 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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template