3

I'm attempting to evaluate a class to see if it contains some text in my click handler, but I can't get my code to act properly. What am I missing?

The if statement is looking to see whether the class of the clicked object has the word "headline" in it.

$('[class^=edit_]').click(function(){
    var element = $(this).attr('class');
    var field = element.split(/_(.+)/)[1];
    if ($(this).attr('[class*=headline]'))
    {
        alert("headline");
    }
    else
    {
        alert("not headline");
    };
});

Is it possible to construct my if statement with something that evaluates the var field = element.split(/_(.+)/)[1]; since that is really where the information resides.

Something like:

if (element *= "headline"){do this};

I'm not sure I understand all of the "evaluators" that exist in JavaScript to know if I can evaluate a string like that.

3
  • 1
    I do not understand this question. Maybe I'm just stupid, but at this point in time I believe that the question is lacking in detail and coherence. Commented Jan 13, 2011 at 0:23
  • 1
    I don't understand what the if statement is supposed to be testing... Commented Jan 13, 2011 at 0:24
  • The if statement is looking to see whether the class of the clicked object has the word "headline" in it. Commented Jan 13, 2011 at 0:31

1 Answer 1

4

Upon re-reading your question, there's an even simpler approach, just check the .className for the string you want using .indexOf(), like this:

if (this.className.indexOf('headline') != -1)

Previous answer:
The closest version to what you have, checking if an element matching a selector is .is(), like this:

if ($(this).is('[class*=headline]'))

But there's another method more appropriate here (if you're checking for a full class, not part of one), you can use .hasClass() like this:

if ($(this).hasClass('headline'))
Sign up to request clarification or add additional context in comments.

10 Comments

hasClass() might not work in this case, assuming his class name is edit_headline for example, is('[class*=headline]') would match, but not hasClass('headline').
Nick, unfortunately, my class has other words separated by _ so I'm trying to decipher if the full class name has the word "headline" anywhere in it.
@Seldaek - Right, that's why there's the note on the second version :) @Ofeargall - the first .is() version will work then :)
Thanks, Nick. if ($(this).is('[class*=headline]')) was exactly what I was looking for. I'm glad you were able to see what I was trying to achieve even if my question was somewhat incomplete.
@Ofeargall - mm not really, .indexOf() is looking for the string, so it's saying "is the string "headline" found in my class attribute at all?"
|

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.