首页 > 解决方案 > 如何使用 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>标签,但没有任何反应;我也用浏览器控制台试过了

// 先感谢您

标签: javascript

解决方案


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来关闭标签。


推荐阅读