Use jquery to remove a div with no children

后端 未结 6 1162
予麋鹿
予麋鹿 2020-12-14 09:23

How can I use jquery to remove a SPECIFIC div that has no children (at least no children that isn\'t whitespace). E.g.

some cont
相关标签:
6条回答
  • 2020-12-14 10:00

    Here is if empty with children then you can point at children and then remove a parent, this dont look at whitespaces it just remove if empty

    so like; if li is empty it removes #removeme

    if (!$("#tabs ul li").length) $('#tabs').remove();
    
    0 讨论(0)
  • 2020-12-14 10:01

    To remove the element with id equal to removeme:

    $("#removeme").remove();
    

    To remove the element with id equal to removeme only if it is empty:

    $("#removeme:empty").remove();
    

    To remove all empty <div>s:

    $("div:empty").remove();
    

    EDIT: If it's not empty, but has whitespace:

    if($.trim($("#removeme").text()) == "") {
      $("#removeme").remove();
    }
    
    0 讨论(0)
  • 2020-12-14 10:04

    I went with:

    $('#outer > div').filter(function (index) { 
        return $(this).children().length < 1; 
    }).remove();
    

    This says:

    • give me all the div children of #outer
    • use filter to get rid of any which have child nodes
    • remove anything we still have selected

    Sadly, this will remove the div if it contains text, which is probably not what the original poster would have wanted. Plain text doesn't count as a child.

    0 讨论(0)
  • 2020-12-14 10:11

    You can also use:

    $('div:empty').remove();

    http://docs.jquery.com/Selectors/empty

    0 讨论(0)
  • 2020-12-14 10:19

    I couldn't find a selector that ignores text nodes, so this is the quickest/dirtiest code snippet I could come up with.

    $("#header").each(function() { 
        if($(this).children().length < 1) 
            $(this).remove() 
    });
    
    0 讨论(0)
  • 2020-12-14 10:22

    I think you want this:

    $('div#outer div:empty').remove();
    

    It will remove all the empty divs inside the div#outer node

    0 讨论(0)
提交回复
热议问题