Skip to content Skip to sidebar Skip to footer

How To Remove A Div With Same Ids But Display='block' And Display='none' In Javascript

I have more than 1 divs with same id, but one has diplay='block' and others have display='none'. I want to delete all the divs which have display='none'. Kindly tell the easiest wa

Solution 1:

It is against W3 Standards to have more than one element in a document to have same id's.

Use class names instead. Unfortunately there is no javascript function to get elements by class name. I am afraid you will have to cycle through all the div elements(using getelementsbytagname) and then find out the necessary div.

However if you are using jquery you can use its selector and get the elements by class name and iterate through it.

$('.classname').each(function(index) {
   //check if display is none and delete it
  });

Solution 2:

You can do that with one line of jquery code if you want to go with it:

$("div.the_div:hidden").remove();

That will remove all the divs due to JQuery's implicit iteration that are hidden that is display:none

Make sure that you wrap above line of code in ready method of JQuery which fires as soon as DOM becomes ready. So it becomes:

$(function(){
    $("div.the_div:hidden").remove();
});

Note: Give your divs the class of the_div first.

Solution 3:

Any html element ID attribute must be unique. More on W3Schools.com. You should rewrite your html code to use classes instead of ids.

Solution 4:

first ID should be unique for the whole document, duplicate ID in the document is wrong practice. about deleting elements who have the same style,if you can keep the styling in CSS class then it is better to create two classes one Hidden and other Displayed then use jQuery to select these elements from the selector and remove them eg

$(".hidden").remove();

but if it was inline you should select the elements and loop through them and see if the who has style = none remove it. eg: lets say all the elements you want to control have unified class instead of duplicate Id, lets say "MyDivs" in jQuery

    $(".MyDivs").each(
    function(){
    if($(this).css("display") == "none")
    {
    $(this).remove();
    }
}
)

hope this helps

Post a Comment for "How To Remove A Div With Same Ids But Display='block' And Display='none' In Javascript"