You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript移除包含指定文本的div元素?

解决方案

问题核心是没有给生成的div绑定可识别的标识,导致移除时无法精准定位对应元素。以下是修复后的完整代码,同时优化了变量声明避免全局污染:

修改后的JavaScript代码

let addBtn = document.getElementById("add-btn");
let removeBtn = document.getElementById("rmv-btn");
let bookArray = [];
addBtn.addEventListener("click", addBook);
removeBtn.addEventListener("click", removeBook);

function addBook() {
  const newBook = document.getElementById("input").value.trim();
  if (newBook) {
    bookArray.push(newBook);
    addElement(newBook);
    clear();
    console.log(bookArray);
  } else {
    clear();
    console.log(bookArray);
  }
}

function removeBook() {
  const inputBook = document.getElementById("input").value.trim();
  const index = bookArray.indexOf(inputBook);
  if (index !== -1) {
    bookArray.splice(index, 1);
    removeElement(inputBook);
    console.log(bookArray);
  }
  clear();
}

function clear() {
  document.getElementById("input").value = "";
}

function addElement(bookText) {
  const newDiv = document.createElement("div");
  newDiv.textContent = bookText;
  // 给div添加数据属性,方便后续查找
  newDiv.dataset.book = bookText;
  // 将div插入到指定容器内,DOM结构更清晰
  const myDiv = document.getElementById("mydiv");
  myDiv.appendChild(newDiv);
}

function removeElement(bookText) {
  // 根据数据属性精准定位目标div
  const targetDiv = document.querySelector(`[data-book="${bookText}"]`);
  if (targetDiv) {
    targetDiv.remove();
  }
}

修改后的HTML代码

<input type="text" id="input" />
<button id="add-btn">Add</button>
<button id="rmv-btn">Remove</button>
<div id="mydiv"></div>

关键优化点

  • 绑定数据标识:生成div时通过dataset.book关联文本内容,移除时直接通过选择器定位元素
  • 规范变量声明:给所有局部变量添加const/let,避免全局变量污染
  • 简化数组操作:用indexOf替代循环查找,代码更简洁高效
  • 优化DOM结构:将生成的div插入到指定容器内,而非body末尾
  • 处理输入空格:添加trim()过滤输入文本的首尾空格,避免无效操作

内容的提问来源于stack exchange,提问作者Sergio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 01:25:22