18
<li style="padding-bottom: 0px; display: none;">
<span> Content </span>
</li>

i want to check display == none

i got the solution with the below script.

if($(this).closest('li').attr('style') =='padding-bottom: 0px; display: none;'){
    // script
}

any other simple way to write. Thanks

0

3 Answers 3

9

The issue you have is that you're mixing jQuery and vanilla JS methods here, with .attr().display. You're also trying to compare the whole style string against (if it worked) one CSS rule.

A better method of achieving this would be to use jQuery's is() method, along with the :visible selector. Try this:

if ($(this).closest('li').is(':visible')) {
  // script
}
Sign up to request clarification or add additional context in comments.

Comments

1

If you want only to check if the element is hidden you can check if the display is set to none using css() method. Using .attr('style') it will return the whole style on the element.

if($(this).closest('li').css('display') == 'none' ){

}

Working demonstrative example (I've put the inline style just for demonstration, but I don't recommend you to use it):

$('li').each(function(i) {
  if ($(this).css('display') == 'none') {
    console.log(i); // logs the indexes of the hidden elements
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li style="padding-bottom: 0px; display: none;">
  <span> Content </span>
</li>
<li style="padding-bottom: 0px; display: none;">
  <span> Content </span>
</li>
<li style="padding-bottom: 0px;">
  <span> Content </span>
</li>

Comments

1

You can use :visible or :hidden selectors directly:

if ( $('li:visible').length > 0 ) {
    // it is visible
}

You can use :visible or :hidden selectors with is():

if ( $('li').is(':visible') ) {
    // it is visible
}

Finally, you can check the specific value of 'display' with css():

if ( $('li').css('display') === 'none' ) {
    // it is hidden
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.