2

I was wondering what would be the difference in these two codes

$('.stars li').each(function(i){

  if(this.style.display !== 'none'){
    this.style.display = 'none';
    return false;
  }
});

and this code

$('.stars li').each(function(i){

  if($(this).css('display', '')){
    $(this).css('display' = 'none');
    return false;
  }
});

why the first one iterate over each li element, however the second one doesn't it stays on the first element?

0

1 Answer 1

1
$(this).css('display', '')

is an expression that evaluates to a value - what it evaluates to is the $(this) jQuery object, which has also had its display changed. So the condition

if($(this).css('display', '')){

will always be satisfied, because objects are truthy.

Use $(this).css('display') === 'none' instead (one argument) to retrieve the current computed display style.

if ($('div').css('display') === 'none') {
  console.log('Div hidden');
} else {
  console.log('Div not hidden');
}

if ($('span').css('display') === 'none') {
  console.log('Span hidden');
} else {
  console.log('Span not hidden');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div></div>
<span style="display: none"></span>

Keep in mind that

this.style.display

checks the display property on the element itself, whereas

$('div').css('display')

checks the computed display property. The element may have a display applied (eg, from CSS like div { display: none }) despite not having a display property of the element's own style object.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you soo much that was clear enough, so I would say its better to use the this.style.display than $('div').css('display') since the div properties has already css by default which is { display: none }

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.