- This topic is empty.
Viewing 13 posts - 1 through 13 (of 13 total)
Viewing 13 posts - 1 through 13 (of 13 total)
- The forum ‘JavaScript’ is closed to new topics and replies.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
Home › Forums › JavaScript › Jquery: If ul has no li
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?
This should do the trick
http://codepen.io/karlpcrowley/pen/JboEi
Super minor optimization: http://codepen.io/ggilmore/pen/biehl
Ah yes, this is why I refactor my code, I always miss ! vs ==0
Perfect guys. Thanks so much for your help.
I’m new to jQuery but very quickly realising the possibilities it opens.
Hi,
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!
You might want to show us your code…
Hi Shikkediel,
Like this one –
< ul >
<∕ul >
<ul >
<li > some data
<∕li >
<∕ul >
Okay, as simple as that… give this a try then:
$('ul').each(function() {
if(!$(this).has('li').length) $(this).html('Sorry, this is empty');
});
Please, don’t!
Don’t put a text message inside the ul
tag. Please, don’t do this:
<ul>
Sorry, this is empty (and wrong)!
</ul>
It’s invalid HTML. Permitted content for ul
tag is zero or more li
elements (https://developer.mozilla.org/en/docs/Web/HTML/Element/ul).
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>');
});
You’re right @nejuzofeco!
Personally I would use pure CSS instead: http://codepen.io/Mottie/pen/ZppzyB
ul:empty {
padding: 0;
}
ul:empty::after {
content: "Sorry this is empty";
color: red;
}
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;
<ul></ul>
Ah, good point!