I am trying to check if my <ul>
has a <li>
element in Jquery, if it does then it displays a div if not it hides it. So far I have the following code:
$(document).ready(function () {
$('#div-1 .div-2').each(function (index, item) {
var colorCount = $(item).find('.item ul li').length;
$(item).attr('data', colorCount);
if (colorCount > 0 ) {
$('.colourClass').show();
}
else {
$('.colourClass').hide();
}
});
});
Is this correct or is there a stricter and better way to do it?
I'd advise you to use toggle() function to achieve your requirements.
const $ul = $('#test'); $('#div').toggle($ul.find('li').length > 0);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul id='test'> <li>asdas</li> </ul> <div id='div' style='display: none;'> Show if li exist! </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.