Search code examples
javascripthtmlprototype

Removing divs on page with attribute display:none via Javascript


There is a plug in that generates some divs on the page and when they are viewed it makes them display:none but all these pile up too much. How can I remove them via Javascript?

<div id="workarea">
<div id="message" class="messages" style="display: none;">Your message was saved</div>
<div id="message" class="messages" style="display: none;">Your message was saved</div>
<div id="message" class="messages" style="display: none;">Your message was saved</div>
<div id="message" class="messages" style="display: none;">Your message was saved</div>
</div>

Now I cant just do $("workarea").innerHTML =""; because there are more things i need in the work area at that point, also there are elements (other divs) that have display:none in the work area that i will want to keep. The best way would be something where i can grab the class like "messages" and make it find all the divs with display:none that have class "message" but how?


Solution

  • Just loop through them and check style.display to see if it's "none":

    // Reminder to lurkers: This is Prototype, not jQuery!
    $("workarea").childElements().each(function(child) {
        if (child.style.display === "none") {
            $(child).remove();
        }
    });
    

    Or if you want to restrict that to child elements of #workarea that have class "messages":

    // Reminder to lurkers: This is Prototype, not jQuery!
    $("workarea").childElements().each(function(child) {
        if (child.style.display === "none" && child.hasClassName("messages")) {
            child.remove();
        }
    });
    

    Or for that matter:

    // Reminder to lurkers: This is Prototype, not jQuery!
    $$("#workarea > .messages").each(function(child) {
        if (child.style.display === "none") {
            $(child).remove();
        }
    });
    

    Side note: The HTML you've quoted is invalid. id values must be unique in the document, you can't have more than one div with the id "message". Doesn't change the answer above, but I thought I should mention it. If those are being generated by a plug-in, I'd suggest using a different plug-in. :-)