Give help. Get help.

  • # January 15, 2013 at 6:41 pm

    Hi Guys,

    I am trying to work out how to check if a UL DOES NOT contain a li … then if it is, add a message to say “sorry this is empty”.

    Any ideas?

    # January 15, 2013 at 6:55 pm

    This should do the trick

    # January 15, 2013 at 6:58 pm

    Super minor optimization:

    # January 15, 2013 at 7:07 pm

    Ah yes, this is why I refactor my code, I always miss ! vs ==0

    # January 15, 2013 at 7:23 pm

    Perfect guys. Thanks so much for your help.

    I’m new to jQuery but very quickly realising the possibilities it opens.

    # July 21, 2016 at 5:43 am

    I was trying this same jQuery code

    if( !$(“ul”).has(“li”).length ) {
    $(“ul”).html(“Sorry, this is empty”);

    with two UL one is empty and the other one has LI inside it.

    What we can do for this?

    I need this for my code. Please help!

    # July 21, 2016 at 8:47 am

    You might want to show us your code…

    # July 21, 2016 at 9:40 am

    Hi Shikkediel,
    Like this one –

    < ul >

    <∕ul >

    <ul >
    <li > some data
    <∕li >
    <∕ul >

    # July 21, 2016 at 1:11 pm

    Okay, as simple as that… give this a try then:

    $('ul').each(function() {
        if(!$(this).has('li').length) $(this).html('Sorry, this is empty');
    # September 9, 2016 at 7:30 am

    Please, don’t!

    Don’t put a text message inside the ul tag. Please, don’t do this:

        Sorry, this is empty (and wrong)!

    It’s invalid HTML. Permitted content for ul tag is zero or more li elements (

    That is, you can’t put a piece of text in that place.

    If you want to show this message, use javascript to replace the ul tag by, for instance, a p tag. Using jQuery, you can do:

    $('ul').each(function() {
        // Will replace "<ul></ul>" by "<p>Sorry, this is empty</p>"
        if(!$(this).has('li').length) $(this).replaceWith('<p>Sorry, this is empty</p>');
    # September 18, 2016 at 5:33 am

    You’re right @nejuzofeco!

    Personally I would use pure CSS instead:

    ul:empty {
      padding: 0;
    ul:empty::after {
       content: "Sorry this is empty";
       color: red;
    # September 18, 2016 at 7:16 am

    Nice, but it would fail in the case of the given example markup due to the new lines being interpreted as a space;

    < ul >
    </ul >
    <ul >
    <li > some data
    </li >
    </ul >

    The demo CSS way only works if the ul start and end tags are butt up to one another and on the same line;

    # September 18, 2016 at 8:47 am

    Ah, good point!

Viewing 13 posts - 1 through 13 (of 13 total)

You must be logged in to reply to this topic.