我有一个JavaScript函数,它附加一个p
标记与类myPara
。
我想检查直到现在元素是否追加:
- 如果追加了 则停止追加
- 如果没有添加,则添加
p
标签
我已经尝试了一些SO问题都是关于jQuery,可以告诉在JavaScript
如何在append后检查元素是否存在?
如何检查追加元素是否已经存在?(重复)
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>
Thanks much in advance
根本不需要checkPara
。只需在appendPara
之外创建para
,这样就可以在添加它的函数中检查。
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
这样的数组方法。
这对你有用吗?
document.getElementById("appendP").addEventListener("click",function(){
let para = document.createElement("p");
para.className = "myPara";
var textnode = document.createTextNode("Dummy is my brother");
para.appendChild(textnode);
document.getElementById("containPara").appendChild(para);
},{once:true})
<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 id="appendP">Append p</button>