我有一个 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/