最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How do you delete a html input element using JavaScript? - Stack Overflow

programmeradmin1浏览0评论

I want to delete the input elements from the table. I could not figure out any way to delete them via JavaScript.

<table><tbody><tr>
<td><input id="c11" value=" " size="1" style="border-width: 0px;" type="text"></input></td>
<td><input id="c12" value=" " size="1" style="border-width: 0px;" type="text"></input></td>
</tr>
</tbody>
</table>

I want to delete the input elements from the table. I could not figure out any way to delete them via JavaScript.

<table><tbody><tr>
<td><input id="c11" value=" " size="1" style="border-width: 0px;" type="text"></input></td>
<td><input id="c12" value=" " size="1" style="border-width: 0px;" type="text"></input></td>
</tr>
</tbody>
</table>
Share edited Dec 12, 2012 at 16:48 curtisk 20.2k4 gold badges60 silver badges74 bronze badges asked Dec 12, 2012 at 16:45 WaseemWaseem 411 gold badge2 silver badges4 bronze badges 2
  • 1 Plain vanilla JavaScript or jQuery? – j08691 Commented Dec 12, 2012 at 16:47
  • possible duplicate of JavaScript: remove element by id – MrCode Commented Dec 12, 2012 at 16:56
Add a ment  | 

6 Answers 6

Reset to default 1

You can do that :

var inputs = document.getElementsByTagName('input');
while (inputs.length) inputs[0].parentNode.removeChild(inputs[0]);

If you have your table element, you could also use myTable.getElementsByTagName('input');.

Demonstration

document.getElementById('c11').outerHTML =  "";

if your using Jquery

Use .remove()

$("#yourtableid tr").remove();

If you want to keep the data for future use even after removing it then you can use .detach()

$("#yourtableid tr").detach();

It's work!

document.getElementById('c11').val("");
document.getElementById('c12').val("");

Try this code

 function removeRow(r)
    {
         var fo = "foo";
         var ido = r.id.substring(3,r.id.length-1);
         for(i=1;i<=3;i++)
         {
            document.getElementById(fo+id0+i).remove();
         }
         document.getElementById(fo+ido+5).nextSibling.remove();  
         document.getElementById(fo+ido+5).remove();
    }

Personally, if you don't have access to jQuery, I would just give the parent element an id and then do this

var els = document.findElementById('tableId').childNodes.getElementByTagName('input');
for( var i = 0; i < els.length; i++){
    els[i].removeNode(true);
}

Alternately, you could substitute the code with something like this for plete browser patibility, as @dystroy pointed out removeNode is only available in IE.

var els = document.getElementById('tableId').getElementsByTagName('input');
while( els.length ){
    els[0].parentNode.removeChild(els[0]);
}​

Something like that should work. Honestly, I would use jQuery. Much easier.

发布评论

评论列表(0)

  1. 暂无评论