laurens1991 laurens1991 - 4 years ago 76
Javascript Question

Targeting certain element if no children

Something that I expected to be rather simple is causing me a lot of headache.

I am trying to check if the a certain element has children, if no children I would like to change the css for the next element

<i>
for that particular instance.

I have managed to get the script to remove all
<i>
elements but it should only remove it from those instances where there are no children found.

I normally manage to get my jquery working with a lot of trial/error, but with this one I'm in the dark even though it can't be very hard. It must be something rather simple I'm missing here.

$( document ).ready(function() {
if ($('nav ul li').find('ul').length = 0) {
$(this).next('i').css('display','none')
}
});


HTML

<ul>
<li>
<input type="checkbox" checked>
<a href="#"><i class="fa fa-chevron-down"></i>prime 1</a>
</li>
<li>
<input type="checkbox" checked>
<a href="#"><i class="fa fa-chevron-down"></i>prime 1</a>
<ul>
<li><a href="#">sub 1</a></li>
<li><a href="#">sub 2</a></li>
</ul>
</li>

Answer Source

Because this inside the if block does not refer to the li element.

You can use the .not() filter method with :has() to do it like

$(document).ready(function() {
  $('nav ul li').not(':has(ul)').next('i').css('display', 'none');
});

Note: I think there is another problem since, i cannot be a sibling element of a li element

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download