Thursday, April 28, 2011

jQuery Remove Div Based On Content

i would like to remove/hide a li based on the content inside it, is this easy to do?

eg. the code below: if span#type has no content then li.grouping should be removed or hidden.

<li class="grouping"><span class="desc">Options:</span><br /><span id="type"></span></li>
From stackoverflow
  • maybe something like

    if ($("span#type").text() == "") {
        $("li.grouping").hide();
    }
    
    peirix : This would hide all "li.grouping" if only one span anywhere was empty.
    Aziz : one span? or one span of class type? I assumed that the page will have only one 'span#type'
  • $("li.grouping:has(span#type:empty)").remove()
    

    It would seem to make more sense if type were a class, rather than an id, as there should only be one element with a given id on the page. In that case:

    $("li.grouping:has(span.type:empty)").remove()
    
    mattt : thanks brian, perfect!
    mattt : sorry brain, almost perfect. the page errors in the case that span.type isn't empty. can we address this? i'm placing the code just before the closing tag. --- $("li.grouping:has(span.type:empty)") is null ---
    Brian Campbell : Hmm. It works fine for me using jquery 1.3.2 in Safari 4 beta and Firefox 3.0.5. http://ephemera.continuation.org/stackoverflow/jquery.html
    Brian Campbell : Note also that placing the code at the end right before the tag is not ideal; instead, you should use $(document).ready(). For example: http://ephemera.continuation.org/stackoverflow/jquery2.html
    mattt : Great, perfect solution Brian. Thanks!

0 comments:

Post a Comment