使用 JavaScript 检查 Div 是否包含特定文本
检查 div 元素是否包含特定文本:
- 使用元素的
textContent
属性获取元素及其后代的文本内容。 - 使用
includes()
方法检查特定文本是否包含在 div 中。 - 如果是,则
includes()
方法返回 true,否则返回 false。
以下是本文示例的 HTML。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<div id="box">
<p>Hello world</p>
<p>One, two, three</p>
</div>
<script src="index.js"></script>
</body>
</html>
这是相关的 JavaScript 代码。
const box = document.getElementById('box');
if (box.textContent.includes('world')) {
console.log('✅ world is contained in div');
} else {
console.log('⛔️ world is NOT contained in div');
}
我们使用 textContent
属性获取 div 元素及其后代的文本内容。
我们使用
String.includes
方法来检查 div 是否包含特定文本。
includes()
方法执行区分大小写的搜索并检查提供的字符串是否包含在调用它的字符串中。
console.log('hello'.includes('lo')); // 👉️ true
console.log('hello'.includes('test')); // 👉️ false
如果要执行不区分大小写的检查文本是否包含在 div
元素中,则必须将元素的文本内容和要检查的字符串转换为小写。
const box = document.getElementById('box');
const word = 'WORLD';
if (box.textContent.toLowerCase().includes(word.toLowerCase())) {
console.log('✅ world is contained in div');
} else {
console.log('⛔️ world is NOT contained in div');
}
通过将我们要比较的两个字符串都转换为小写,我们能够执行不区分大小写的比较。
如果 div
元素的文本内容包含特定文本,我们的 if
块将运行,否则运行 else
块。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。