Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript/jQuery "if" condition syntax

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.

like image 774
Ofeargall Avatar asked May 07 '26 02:05

Ofeargall


1 Answers

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'))
like image 80
Nick Craver Avatar answered May 09 '26 16:05

Nick Craver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!