Javascript 如何在单击按钮时删除DOM元素

Javascript 如何在单击按钮时删除DOM元素,javascript,html,Javascript,Html,您需要将单击的元素传递给函数 $(this).parents('label').remove(); 演示:-支持的IE>=9更新您的onclicks以将此传递到函数中: function removeDOM(el) { el.parentNode.removeChild(el.previousElementSibling) } …然后在removeDOM中,可以使用参数的previousSibling或previousElementSibling属性 onclick="removeD

您需要将单击的元素传递给函数

$(this).parents('label').remove();

演示:-支持的IE>=9

更新您的
onclick
s以将
传递到函数中:

function removeDOM(el) {
    el.parentNode.removeChild(el.previousElementSibling)
}
…然后在
removeDOM
中,可以使用参数的
previousSibling
previousElementSibling
属性

onclick="removeDOM(this); return false"
假设兄弟姐妹在那里。如果可能不是:

function removeDOM(element) {
    element.previousElementSibling.remove();
}
实例:

函数删除对象(元素){
if(element.previousElementSibling){
element.previousElementSibling.remove();
}
}

Abcd1
Abcd1
Abcd1
您可以使用,请尝试以下代码:

function removeDOM(element) {
    if (element.previousElementSibling) {
        element.previousElementSibling.remove();
    }
}
那么就这样称呼它:

  function removeDOM(button) {
    var previuosLabel;
    // always remove the white space between the button and the label
    while((button.previousSibling).nodeType !== 1) { 
            button.parentNode.removeChild((button.previousSibling));
    } 
    previuosLabel=button.previousSibling;
    if(previuosLabel.nodeType === 1) { 
        button.parentNode.removeChild(previuosLabel);
    }  
  }

这将始终检查
按钮
标签
之间是否有空格,并在移除
标签
之前将其移除,在这种情况下,确保将移除标签


您需要
.prev().remove()
@Petroff:这里没有
jquery
标记。@chsdk它是
previouselement同级
不是
previousSibling
function removeDOM(element) {
    if (element.previousElementSibling) {
        element.previousElementSibling.remove();
    }
}
  function removeDOM(button) {
    var previuosLabel;
    // always remove the white space between the button and the label
    while((button.previousSibling).nodeType !== 1) { 
            button.parentNode.removeChild((button.previousSibling));
    } 
    previuosLabel=button.previousSibling;
    if(previuosLabel.nodeType === 1) { 
        button.parentNode.removeChild(previuosLabel);
    }  
  }
<input type="button" onclick="removeDOM(this); return false;" />