views:

46

answers:

4

How do you check if the class that is assigned to a div? For example, I want to check if a div has a class of header-link then it should alert a message box similar to this:

$('.header a').click(function()
{
    if($(this).classname == 'header-link')
    {
        alert('the element has the class name already');
    }
    else
    {
        $(this).addClass('header-link');
    }
});

The classname I put in there is an example I need to make it check if it has the class assigned or not... (even when jQuery has assigned it dynamically).

+2  A: 

Sounds like you want .hasClass()

$('.header a').click(function()
{
    if($(this).hasClass('header-link'))
    {
        alert('the element has the class name already');
    }
    else
    {
        $(this).addClass('header-link');
    }
});
macca1
+1  A: 

use the $(this).hasClass('header-link') function It returns true if the element has the class you specify

edit: updated for validity

lock
+1  A: 

$(this).hasClass("header-link")

Chubas
+5  A: 

The correct check is .hasClass() like this:

$('.header a').click(function() {
  if($(this).hasClass('header-link')) {
    alert('the element has the class name already');
  } else {
    $(this).addClass('header-link');
  }
});

but...do you even need this check? If the element already has the class .addClass() won't add a duplicate, so if that's your worry don't check, just call .addClass('header-link') like this:

$('.header a').click(function() {
  $(this).addClass('header-link');
});
Nick Craver