jQuery - find a class exist and return true/false
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($('li.show-more ul li').hasClass('defined')) {
$('li.show-more > a').addClass('selected');
}
I assume that's what you intended with typeof
?
Another option:
var active_sub_menu = $('li.show-more ul li').find('.selected');
if(active_sub_menu.length) {
$('li.show-more > a').addClass('selected');
}