问题描述:

This question already has an answer here:

  • What do querySelectorAll, getElementsByClassName and other getElementsBy* methods return?

    6 answers

网友答案:

Assuming parent really is the direct parent of the boxes, you'd have to iterate and remove each one

function remove_textbox(){
    var parent   = document.getElementById("div1");
    var children = document.getElementsByName("textbox1");

    for( var i=children.length; i--; ) {
        parent.removeChild(children[i]);
    }
}

function remove_textbox(){
    var parent   = document.getElementById("div1");
    var children = document.getElementsByName("textbox1");

    for( var i=children.length; i--; ) {
        parent.removeChild(children[i]);
    }
}

document.getElementById('test').addEventListener('click', remove_textbox)
<div id="div1">
    <input type="text" name="textbox1">
    <input type="text" name="textbox1">
    <input type="text" name="textbox1">
    <br /><br />
    <button id="test">Remove inputs</button>
</div>
网友答案:

getElementsByName returns collection. So you need to remove these elements one by one.

function remove_textbox(){
    var parent=document.getElementById("div1");
    var children=document.getElementsByName("textbox1");
    var index;
    for (index = children.length - 1; index >= 0; index--) {
    parent.removeChild(children[index]);
    }

    }
网友答案:

try this

function remove_textbox(){
    var parent = document.getElementById("div1");
    var child = document.getElementsByClassName("textbox1")[0];
    parent.removeChild(child);
}

remove_textbox();
网友答案:

function remove_textbox(){
  var parent=document.getElementById("div1");
  [].slice.call(document.getElementsByName("textbox1")).forEach(
    function (child) { parent.removeChild(child); } );
}

document.getElementsByTagName('button')[0].onclick = remove_textbox;
<div id="div1">
  <input name="textbox1">
  <input name="textbox1">
  <button>Remove</button>
</div>
相关阅读:
Top