How to remove div with the same ids, but display = 'block' and display = 'none' in JAVascript

I have more than 1 divs with the same id, but one has diplay = 'block' and others have display = 'none'.

I want to remove all divs that have display = 'none'.

Please tell us the easiest way.

+2


a source to share


4 answers


It is against the W3 standards to have more than one element in a document in order to have the same IDs.

Use class names instead. Unfortunately there is no javascript function to get elements by class name. I'm afraid you will have to iterate over all the divs (using getelementsbytagname) and then find out the required div.



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

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

      

+6


a source


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

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

      

This will remove all divs due to JQuery hidden iteration hidden iteration which isdisplay:none



Make sure you complete the line of code in the jQuery ready method that runs as soon as the DOM is ready. This is how it is done:

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

      

Note. First give your divs a class the_div

.

+4


a source


Any html element id attribute must be unique. Learn more about W3Schools.com . You should rewrite your html code to use classes instead of ids.

+2


a source


The first identifier must be unique for the entire document, duplicate identifier in a document is a bad practice.

about removing elements that have the same style, if you can keep the style in a CSS class, then it is better to create two classes, one is "Hidden" and the other. Will display, then use jQuery to select these elements from the selector and remove them, like

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

      

but if it was inline you should select the elements and skip them and see if anyone has the style = no. eg: lets say all the elements you want to control have a unified class instead of a duplicate id, lets say "MyDivs"
in jQuery

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

      

hope this helps

+1


a source







All Articles