问题描述
我正在尝试使用 javascript 从页面中删除所有带有按钮或输入标签的标签...到目前为止,我的代码删除了其中一些,但我不知道为什么.它只删除了许多复选框中的一个,以及 2 个按钮(有 3 个按钮)
I'm trying to use javascript to remove everyhting with button or input tags from a page... So far my code removes some of them and I dont know why. It only removes one checkbox out of many, and 2 buttons (there are 3 buttons)
var buttons = document.getElementsByTagName("button");
for (var j = 0; j < buttons.length ; j++)
{
buttons[j].parentNode.removeChild(buttons[j]);
}
var checkboxes = document.getElementsByTagName("input");
for (var j = 0; j < buttons.length ; j++)
{
checkboxes[j].parentNode.removeChild(checkboxes[j]);
}
推荐答案
var checkboxes = document.getElementsByTagName("input");
for (var j = 0; j < buttons.length ; j++) // You use the wrong variable here
{
checkboxes[j].parentNode.removeChild(checkboxes[j]);
}
应该是;
for (var j = 0; j < checkboxes.length ; j++)
关于未删除的按钮,可能是因为它是input type="button"
而不是<button>
?
Regarding to the undeleted button, maybe it's because it's an input type="button"
and not a <button>
?
请注意,document.getElementsByTagName("input");
稍后将获取并删除所有输入,而不仅仅是复选框!
Note that document.getElementsByTagName("input");
will get and delete later all the inputs, not just the checkboxes!
我可以建议您使用像 jQuery 这样的 javascript 库吗?你可以用一行代码毫无问题地做到这一点:
May I suggest you using a javascript library like jQuery? you could have done this will one line of code with no problems:
$('input[type="button"], input[type="checkbox"], button').remove();
这篇关于javascript试图删除带有特定标签的所有东西的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!