说明
text()
:获取匹配元素集合中每个元素的合并文本内容,包括它们的后代,或设置匹配元素的文本内容,类似于dom.innerTexthtml()
:获取匹配元素集合中第一个元素的HTML内容,或设置每个匹配元素的HTML内容,类似于dom.innerHTML
示例
获取纯文本内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="js/jquery-3.7.1.js"></script>
<style>
body {
font-size: 24px;
}
</style>
</head>
<body>
<span>span1</span>
<span>span2</span>
<span>span3</span>
<div>div1<br /></div>
<div>div2<br /></div>
<div>div3<br /></div>
<script>
const $spans = $('span')
const $divs = $('div')
console.log($spans.text())
console.log($divs.text())
</script>
</body>
</html>
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/1d9577375bc4414b9f00909bd943d03f.png)
获取html内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="js/jquery-3.7.1.js"></script>
<style>
body {
font-size: 24px;
}
</style>
</head>
<body>
<span>span1</span>
<span>span2</span>
<span>span3</span>
<div>div1<br /></div>
<div>div2<br /></div>
<div>div3<br /></div>
<script>
const $spans = $('span')
const $divs = $('div')
console.log($spans.html())
console.log($divs.html())
</script>
</body>
</html>
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/2d3589c22caa49c98f6c4850bd6f986d.png)
设置纯文本内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="js/jquery-3.7.1.js"></script>
<style>
body {
font-size: 24px;
}
</style>
</head>
<body>
<span>span1</span>
<span>span2</span>
<span>span3</span>
<div>div1<br /></div>
<div>div2<br /></div>
<div>div3<br /></div>
<script>
const $spans = $('span')
const $divs = $('div')
$spans.text('<h1>h1标题标签</h1>')
$divs.text('<h1>h1标题标签</h1>')
</script>
</body>
</html>
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/2182c68372d2497d99f3cd0bf7b1a8b0.png)
设置html内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="js/jquery-3.7.1.js"></script>
<style>
body {
font-size: 24px;
}
</style>
</head>
<body>
<span>span1</span>
<span>span2</span>
<span>span3</span>
<div>div1<br /></div>
<div>div2<br /></div>
<div>div3<br /></div>
<script>
const $spans = $('span')
const $divs = $('div')
$spans.html('<h3>h3标题标签</h3>')
$divs.html('<h3>h3标题标签</h3>')
</script>
</body>
</html>
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/3e82337c62df46fc9c101bcd00497b35.png)