使用 Javascript 或 Jquery 删除 DIV 标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4755546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:56:37  来源:igfitidea点击:

Remove DIV tag using Javascript or Jquery

javascriptjqueryhtml

提问by Sanjai Palliyil

How do I remove a DIV with a specific value?

如何删除具有特定值的 DIV?

<div value="0" class="task_row"></div>

I want to remove the above div which has value 0.

我想删除上面的值为 0 的 div。

回答by Elian Ebbing

As Ben Rowe points out in the comments, valueis not a valid attribute of the div tag. And both the jQuery solution and the solution that uses getElementsByTagName()has to iterate through a list, which is bad for performance. I think that creating an idattribute instead is a better option:

正如 Ben Rowe 在评论中指出的那样,value不是 div 标签的有效属性。并且 jQuery 解决方案和使用的解决方案getElementsByTagName()都必须遍历列表,这对性能不利。我认为创建一个id属性是一个更好的选择:

<div id="task_row_0" class="task_row"></div>

And then you can just do:

然后你可以这样做:

var div = document.getElementById("task_row_" + taskId);
div.parentNode.removeChild(div);

回答by Жасулан Бердибеков

this is jquery code )):

这是 jquery 代码)):

$('div').each(function(){
  if($(this).attr('value') == '0'){
    $(this).remove();
  }
});

回答by sdleihssirhc

var divs = document.getElementsByTagName('div');
for(var i = divs.length; i; i -= 1) {
    if (divs[i].getAttribute('value') == 0) {
        divs[i].parentNode.removeChild(divs[i]);
    }
}

回答by Andrew

Edit: Nevermind - Zhasulan beat me to it. :P

编辑:没关系 - 扎苏兰打败了我。:P

With jQuery -

使用 jQuery -

$('div').each(function(){
    if($(this).attr('value') == '0') {
        $(this).hide();
        }
    });

回答by Aamir Shahzad

Alternative to jQuery/JavaScript you can achieve it via CSS only -

替代 jQuery/JavaScript,您只能通过 CSS 实现它 -

JSFIDDLE

JSFIDDLE

div[value="0"] {
    display: none;
}

Or via jQuery using attribute selector:

或者通过 jQuery 使用属性选择器:

JSFIDDLE

JSFIDDLE

$("div[value='0']").hide(); /*.remove() as per your requirement*/