Mircea
Mircea

Reputation: 11623

jQuery check if element have specific attribute

I am trying to see if an element have a specific CSS attribute. I am thinking at something like this:

if ( !$(this).attr('font-style', 'italic')) {
alert ("yop")
}
else {
alert ("nope")
}

It does not work. Any tips on this? Thank you!

Upvotes: 4

Views: 6243

Answers (6)

Nick Craver
Nick Craver

Reputation: 630637

You want this:

if ( $(this).attr('font-style') !=  'italic') {
  alert ("yop")
}
else {
  alert ("nope")
}

Upvotes: 0

karim79
karim79

Reputation: 342795

Here's a simple plugin to do that (tested):

$.fn.hasCss = function(prop, val) {
    return $(this).css(prop.toLowerCase()) == val.toLowerCase();
}

$(document).ready(function() {
    alert($("a").hasCss("Font-Style", "Italic"));
});

<a style="fonT-sTyle:ItAlIc">Test</a>

Upvotes: 5

Mark Schultheiss
Mark Schultheiss

Reputation: 34227

Try a morf of the conditional and a few semi columns added:

$(document).ready(function()
{
    $('#selectable1 span').live('click', function()
    {
        if ($(this).css('font-style') != "italic")
        {
            alert("yop");
        } 
        else
        {
            alert("nope");
        };
    });
}); 

NOTE: Making assumption regarding the select and subsequent markup based on other comments - would need to see the html to make sure on that.

Upvotes: 0

ant
ant

Reputation: 22948

How about this

 if ($(this).css('font-style', 'italic')) {
    alert ("yes")
    }
    else {
    alert ("nop")
    }

But I'd rather use console.log instead of alert if I were you, use firebug its less annoying and more fun :D

<script>

     $(document).ready(function(){ 
         $('#selectable1 span').live('click', function() { 
            if (!($(this).css("font-style","italic"))){ 
                alert ("yop"); 
              } else { 
                alert ("nope"); 
              } 
         }); 
     }); 

</script> 

I don't see why this shouldn't work..

Upvotes: 1

Ikke
Ikke

Reputation: 101261

You are trying to get a css style. The css method can get the information

if ( !$(this).css('font-style') == "italic") {
    alert ("yop")
}
else {
    alert ("nope")
}

Upvotes: 4

Orentet
Orentet

Reputation: 2363

you can get the font-style element and use == operator to get true/false value:

if($(this).attr('font-style') == 'italic')
{
    alert('yes')
}
else
{
    alert('no')
}

Upvotes: 1

Related Questions