javascript - 如何使用 querySelector 删除“p”标签
问题描述
我正在使用 querySelector 删除包含 my 的“p”标签;HTML 中的最后三个;但是我写的代码不起作用
//html
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
I have an <h1>This is my todo list</h1>
// with five <p> tags
<p>I have to study databases </P>
<p>I have to study jquery</P>
<p> I have to continue my workouts</P>
<p>I have to receive my degree </P>
<p>I have to thank my instructors</P>
<script src="note.js"></script>
</body
</html>
//JavaScript
const paragraphs = document.querySelector('p')
paragraphs.forEach(function(paragraph){
if(paragraph.textContent.includes('my')) {
paragraph.remove()
}
})
我想从浏览器中删除最后三个<p>
标签,但没有任何反应;我也用浏览器控制台试过了
// 先感谢您
解决方案
Document.querySelector()
返回第一个匹配的元素。由于它不返回NodeList,因此结果没有forEach()
. 要定位您必须使用的所有元素Document.querySelectorAll()
:
Document 方法
querySelectorAll()
返回一个静态(非实时)NodeList,表示与指定选择器组匹配的文档元素列表。
改变
const paragraphs = document.querySelector('p')
至
const paragraphs = document.querySelectorAll('p')
const paragraphs = document.querySelectorAll('p')
paragraphs.forEach(function(paragraph){
if(paragraph.textContent.includes('my')) {
paragraph.remove()
}
});
<p>I have to study databases </p>
<p>I have to study jquery</p>
<p> I have to continue my workouts</p>
<p>I have to receive my degree </p>
<p>I have to thank my instructors</p>
请注意:虽然它有效,但您不应该使用大写P
来关闭标签。
推荐阅读
- c - C for循环,如何不断提示用户?
- python - 我的 Discord Bot 不在线程内启动 (Discord.py)
- node.js - 为什么当我尝试创建数据时会引发此错误?
- python - 列出更高范围的变量
- javascript - 如何实现具有权重比例节点高度的 Highcharts sankey 图
- flutter - 有没有一种方法可以让我们在后台运行应用程序?
- amazon-cognito - 如何在 AWS Cognito 中取消密码重置?
- visual-studio-code - 当焦点在终端上时,有什么方法可以通过键盘快捷键在 VScode 中切换窗口?
- android - 如何在 RecyclerView 的适配器本身中获得以前的位置?
- javascript - 了解这段代码中的回调函数