2

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).

1
  • 1
    I'm curious as to why you're checking if it already has the class? Commented Sep 27, 2010 at 0:24

4 Answers 4

5

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');
});
Sign up to request clarification or add additional context in comments.

Comments

4

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');
    }
});

Comments

1

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

edit: updated for validity

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.