I want to check if class exists inside a child of li
and if class exists return true
or defined
.
HTML
<li class="show-more">
<a> if found selected then add to this</a>
<ul>
<li><a> sub-menu</a></li>
<li><a> sub-menu</a></li>
<li><a class="selected"> sub-menu</a></li>
<li><a> sub-menu</a></li>
</ul>
</li>
here is my code, but wont return true or false, it return the url of anchor
var active_sub_menu = $('li.show-more ul li').find('selected');
alert(active_sub_menu);
if(typeof active_sub_menu == 'defined'){
$('li.show-more > a').addClass('selected');
}
please dont suggest to use CSS, I just need javascript
Why not simply go for .hasClass()
or length
:
if ( $("selector").length ) { /*EXISTS (greater than 0) */ }
or
if ( $("selector")[0] ) { /*EXISTS (not undefined) */ }
or
if ( $("selector").hasClass("someClass") ) { /*EXISTS (has class) */ }
$('.show-more').each(function () {
if ( $(this).find("li a.seleted").length ) {
console.log('FOUND');
$(this).children("a").addClass('selected'); // Make main anchor also selected
} else {
console.log('NOT FOUND');
}
});
.selected {
background: red;
}
<ul>
<li class="show-more">
<a> if found .selected then add also to this anchor</a>
<ul>
<li><a> sub-menu</a></li>
<li><a> sub-menu</a></li>
<li><a class="selected"> sub-menu</a></li>
<li><a> sub-menu</a></li>
</ul>
</li>
</ul>
<script src="//code.jquery.com/jquery-3.1.0.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With