value - jquery not hasclass




jQuery determine if ul has class OR another one (5)

Do it like this instead, separating it in two bits:

if ($('#menu-item-49').hasClass('current-menu-item') || $('#menu-item-49').hasClass('current-menu-parent') ){
   $('ul.sub-menu ').css('display', 'block');
}

Hope this helps you

what is the right way to determine if an object has one class OR another one? The following is appearantly wrong..

if ($('#menu-item-49').hasClass('current-menu-item' || 'current-menu-parent') ) {
  $('ul.sub-menu ').css('display', 'block');
}

Thanks!


So close!

Try:

if ($('#menu-item-49').hasClass('current-menu-item') || $('#menu-item-49').hasClass('current-menu-parent') ) {
  $('ul.sub-menu ').css('display', 'block'); 
}

You can also use .is() to check for any class beginning with current-menu- by using:

if ( $('#menu-item-49').is('[class]^="current-menu-"') ) {
    //49 is the current menu!
}

More attribute selectors like ^= may be found here.


You cannot use the || (or) operator within hasClass. Try this:

if ($('#menu-item-49').hasClass('current-menu-item') || 
    $('#menu-item-49').hasClass('current-menu-parent')) {
  $('ul.sub-menu ').css('display', 'block');
}

Or you can do this if that's too verbose:

var $menuItem = $('#menu-item-49');
if ($menuItem.hasClass('current-menu-item') || 
    $menuItem.hasClass('current-menu-parent')) {
  $('ul.sub-menu ').css('display', 'block');
}

Or even better:

var $menuItem = $('#menu-item-49');
if ($menuItem.is('.current-menu-item, .current-menu-parent')) {
  $('ul.sub-menu ').css('display', 'block');
}

if ($('#menu-item-49').hasClass('current-menu-item') || $('#menu-item-49').hasClass('current-menu-parent') ) {
  $('ul.sub-menu ').css('display', 'block');
}

Have you tried the following?





if-statement