Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - find a class exist and return true/false

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

like image 552
user007 Avatar asked Feb 15 '13 01:02

user007


1 Answers

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>
like image 84
Roko C. Buljan Avatar answered Sep 20 '22 09:09

Roko C. Buljan