简体   繁体   中英

JQuery - How to check if a span has a class and add a class if one doesnt exist

I need help with some jquery code to check if a span has a class. If it doesn't have a class then add class customtab to this span. How can I do this in jquery?

Here's example html menu.

<div class="menu">
    <ul>
        <li><a class="user_menu_link" href="#"><span class="menu1">Menu Item 1</span></a><li>
        <li><a class="user_menu_link" href="#"><span class="menu2">Menu Item 2</span></a></li>
        <li><a class="user_menu_link" href="#"><span class="menu3">Menu Item 3</span></a></li>
        <li><a class="user_menu_link" href="#"><span class="menu4">Menu Item 4</span></a></li>
    <li><a href="#"><span>Menu Item 5</span></a></li>
    </ul>
</div>

Here's the code I'm trying to use but doesn't work.

$('ul a').each(function() {
  if ($(this).attr('class') == "") {
    $(this).find('span').addClass("customtab");
  }
});

I was able to use this code to make it work.

$('ul a').each(function() {
  if ($(this).attr('class') === undefined) {
    $(this).find('span').addClass("customtab");
  }
});

What class are you checking for and when, eg on click, when the page is loaded, hover, etc.

To check, there is a hasClass method:

// $(this) being the element you are checking for the class
// this could be inside a click function for example
if ($(this).hasClass('menu1')) {
    $(this).addClass('customtab');
}

Update

To check for no class attribute, try this:

if ($(this).attr('class') === undefined) {
    $(this).addClass('customtab');
}

If you don't know what $(this) is then you can find the element by looping through the elements:

$('li a.user_menu_link span').each(function() {
    if ($(this).attr('class') === undefined) {
        $(this).addClass('customtab');
    }
});

http://jsfiddle.net/992g694f/

Fiddle with fixed HTML - http://jsfiddle.net/992g694f/1/

Update 2

$('ul a').each(function() { 
    if($(this).attr('class') === undefined){    
        $(this).find('span').addClass("customtab"); 
    }
});

Try :

$(".menu a span").filter(function() {
    return this.className == '';
}).addClass('customtab');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM