16

How do I remove a DIV with a specific value?

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

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

2
  • 4
    Are you using a javascript library? Is jQuery going to be an acceptable answer? If so, you can do this if jQuery: $('[value="0"]').remove(); Commented Jan 21, 2011 at 5:02
  • 3
    value is not a valid attribute of the div tag. Commented Jan 21, 2011 at 5:04

5 Answers 5

46

As Ben Rowe points out in the comments, value is 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 id attribute instead is a better option:

<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);
Sign up to request clarification or add additional context in comments.

3 Comments

Let's be realistic here. There's zero need for jQuery to do something simple such as this.
Let's be even more realistic here. Tons of people use jQuery, so if they're already using it, why wouldn't they go for a simple single line of code. [+1 for this answer though because I happen to not be using jQuery at the moment]
jQuery eats computer resources and hangs browsers when opened on several tabs, so please dont use it!
4

this is jquery code )):

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

Comments

3
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]);
    }
}

1 Comment

I use your snippet code, but it had error. initial value for i and end condition are not valid
2

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

With jQuery -

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

Comments

0

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

JSFIDDLE

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

Or via jQuery using attribute selector:

JSFIDDLE

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.