简体   繁体   English

使用 javaScript 删除然后添加元素

[英]removing and then adding element with javaScript

When a button is clicked, I want to add an element to my DOM.单击按钮时,我想向我的 DOM 添加一个元素。 But first, I want to remove the previous one I added (in the previos click).但首先,我想删除我添加的前一个(在上一个单击中)。 Inside the click handler I wrote:在点击处理程序中,我写道:

document.getElementById("myId").remove();
var myP = document.createElement("p");
myP.setAttribute("id","myId");
myP.innerHTML = "asdf";
document.getElementById("myDiv").appendChild(myP); 

but it's not working, the "p" does not get added to the DOM.但它不起作用,“p”没有被添加到 DOM 中。

note: I want to use only javaScript, and I want to use "remove()" and not innerHTML = "".注意:我只想使用 javaScript,我想使用“remove()”而不是 innerHTML =“”。

You can also use remove in if block.您也可以在 if 块中使用remove At first, you are removing the element which may or may not be there in DOM.首先,您要删除 DOM 中可能存在或不存在的元素。 If you are adding dynamically and you are writing something that I've done then remove doesn't work because element is not in DOM, so conditional check is only option.如果您正在动态添加并且正在编写我已经完成的内容,则删除不起作用,因为元素不在 DOM 中,所以条件检查是唯一的选择。

 const removeBtnID = document.querySelector( "#removeID" ); removeBtnID.addEventListener( 'click', function removeElement() { const myDiv = document.querySelector( '#myDiv' ); const myId = document.querySelector("#myId"); if ( myId ) { myId.remove(); // or // myDiv.removeChild('myId'); console.log( 'After removing child' ); } const myP = document.createElement("p"); myP.setAttribute("id", "myId"); myP.innerHTML = "asdf"; myDiv.appendChild(myP); })
 <div id="myDiv"></div> <button id="removeID">remove</button>

I have tried your code and it works fine.我试过你的代码,它工作正常。 Just create a new HTML file and use the following code, in order to test it.只需创建一个新的 HTML 文件并使用以下代码进行测试。 Maybe you are missing an id in the javascript code.也许您在 javascript 代码中缺少一个 id。

<!DOCTYPE html>
<html>
    <head>
        <script>
            function clickTest(){
                document.getElementById("myId").remove();
                var myP = document.createElement("p");
                myP.setAttribute("id","myId");
                myP.innerHTML = "asdf";
                document.getElementById("myDiv").appendChild(myP);
            }
        </script>
    </head>
    <body>
        <div id="myId" style="border:1px solid black;">
            TEST
        </div>
        <div id="myDiv" style="border:1px solid red;">
            TEST2
        </div>
        <br/>
        <button onclick="clickTest();">CLICK ME</button>
        
    </body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM