javascript - 如何在 JavaScript 中检查元素是否已附加

标签 javascript html

我有一个 JavaScript 函数,它附加一个带有 myPara 类的 p 标签。

我想检查到目前为止元素是否已附加:

  • 如果已附加,则停止下一次附加
  • 如果未附加,则附加 p 标签

我尝试过一些关于 jQuery 的问题,可以用 JavaScript 来判断

How to check for the existence of an element after append?

How can I check if append element already exists? [duplicate]

function appendPara() {
  let para = document.createElement("p");
  para.className = "myPara";
  var textnode = document.createTextNode("Dummy is my brother");
  para.appendChild(textnode);
  document.getElementById("containPara").appendChild(para);
}

function checkPara() {
  //if (more than 1 length of class ="dummyPara" present)
    //appendPara() will not append next element
//} else {
  //appending will take place by appendPara()
//}
}
<div id="containPara">
  <p class="dummyPara">I am dummy plz don't remove me. You get a chance on next appendings but leave the 1st on he is my brother from another mother</p>
</div>
<button onclick="appendPara()">Append p</button>
<button onclick="checkPara()">Check appending</button>

提前非常感谢

最佳答案

您根本不需要checkPara。只需创建 para 外部 appendPara,它允许检查添加它的内部函数。

const para = document.createElement("p");
para.className = "myPara";
const textnode = document.createTextNode("Dummy is my brother");
para.appendChild(textnode);
const containPara = document.getElementById("containPara");

function appendPara() {
  if (![...containPara.children].includes(para))
    containPara.appendChild(para);
}
<div id="containPara">
  <p class="dummyPara">I am dummy plz don't remove me. You get a chance on next appendings but leave the 1st on he is my brother from another mother</p>
</div>
<button onclick="appendPara()">Append p</button>

[...containPara.children]

将元素子节点扩展到数组中,这允许在其上使用诸如 includes 之类的数组方法。

关于javascript - 如何在 JavaScript 中检查元素是否已附加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69326142/

相关文章:

javascript - 在 Twitter 的关注按钮中隐藏单词 "followers"

javascript - 通过单击正文隐藏元素,除非特定元素

javascript - Google map 库地点和几何图形在一个 HTML 页面中协同工作

HTML 页面更改未显示在用户的 Chrome 浏览器中

javascript - 具有不同名称的特征/变量的 d3 多线图

javascript - 如何在 IE6/7 中获取 textarea 行高

html - 在图像标签中复制 background-img 属性

javascript - 在 JavaScript 中将对象添加到多维数组

html - 使用 Slim Select 的可折叠 Div 中的 Z-Index 与溢出

html - 如何根据视口(viewport)宽度(css3)居中标题