使用DOM删除元素

时间:2015-10-06 22:24:01

标签: javascript html html5 dom

我试图用输入创建一个出现和消失的效果。当单选按钮为" no"时,该项目应该出现。当单选按钮是"是"时,该项目应该消失。我到目前为止已经有了该项目,但无法通过DOM删除它。我已经将我的示例包含在如何删除我已注释掉的电子邮件中,但似乎无法删除innerHTML或输入。

<!DOCTYPE html>
<html>
    <head>        
    </head>
    <body>
        <script>

function myFunction() {
    var label = document.createElement("label");
    label.innerHTML = "<br>Shipment Cost : $";

    var x = document.createElement("INPUT");
    x.setAttribute("type", "text");

    var sp2 = document.getElementById("emailP");
    var parentDiv = sp2.parentNode;
    parentDiv.insertBefore(x, sp2);
    parentDiv.insertBefore(label, x);

    alert("Added Text Box");

}
function myFunction2() {
    alert("Removed Textbox and Input");
    anchor = document.getElementById("label");
    anchor.parentNode.removeChild(anchor);
    anchor2 = document.getElementById("INPUT");
    anchor2.parentNode.removeChild(anchor2);
    //THIS WORKS TO REMOVE EMAIL.
    //anchor3 = document.getElementById("emailP");
    //anchor3.parentNode.removeChild(anchor3);
}

        </script>
<form action="#" method="post" onsubmit="alert('Your form has been submitted.'); return false;">

  <p class="boldParagraph" id="tip3P">Shipping costs are free:</p>
  <input type="radio" name="tip3" value="3" onclick="myFunction2()" />Yes
  <input type="radio" name="tip3" value="4" onclick="myFunction(); this.onclick=null;" />No

  <p class="boldParagraph" id="emailP">Email of seller:</p>



  <input class="averageTextBox" type="email" id="emailAddress" value="" required>

  <br>
  <br>
  <button>Submit</button>

</form>
    </body>
</html>

1 个答案:

答案 0 :(得分:2)

它不起作用,因为行anchor = document.getElementById("label");anchor2 = document.getElementById("INPUT");正在寻找ID为labelinput的元素,但不能找到他们。这些实际上是标签名称。

您需要在第一个函数中为您创建的元素添加一个id:

label.setAttribute("id", "idForLabel");
x.setAttribute("id", "idForInput");

然后将第二个函数中的行更改为:

anchor = document.getElementById("idForLabel");
anchor2 = document.getElementById("idForInput");