jQuery check if element has a specific style property (display)

I need to have a if/else statement inside a function. How do you check if an element (e.g. #cadrage) has a display style property? This is what I have found around the net and yet, it is not working..

if( $('#cadrage').attr('style').display == 'block' ) {
      // do something
} else {
      // do something
}

Answers:

Answer

The jQuery .css() function seems to be what you want.

if( $('#cadrage').css('display') == 'block' ) {
   console.log('It equal block');
} else {
   console.log('It did not equal block');
}

http://jsfiddle.net/SamMonk/FtP6W/

Answer

Your code doesn't work because style property only contains inline styles, not those coming from a stylesheet.

To get the computed style, you can use css method:

$('#cadrage').css('display') == 'block'
Answer

Try this:

if( $('#cadrage').css('display')== 'block' ) {
      // do something
} else {
      // do something
}
Answer

You can get your element display property with the following code snippet

$('#cadrage').css('display');

Note that the css method can return any css property of your element so it is very handy. Therefore your statement code will be:

if( $('#cadrage').css('display').display == 'block' ) {
      // do something
} else {
      // do something
}
Answer

Not exactly what you ask for, but perhaps what you are looking for...

You can use the :visible pseudo selector to check if the element is visible:

if( $('#cadrage').is(':visible')) {
      // do something
} else {
      // do something
}

Note that this doesn't actually check the display style, but rather if the element has a size so that it could be seen in the page.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.