0

Why does the following code won't work in IE browsers (7 and 8)?

$("ul li").each(function() {
  if(($.trim($(this).attr("style"))) != "display: none;"){
     //if content
  }else if(($.trim($(this).attr("style"))) == "display: none;"){
     //else content
  }
});

Note: The first 4 li elements do not not have "style" attribute and the remaining 8 do.

3
  • 1
    Hack could we plese see the html that goes wiht this ? Commented May 31, 2011 at 13:30
  • 1
    you could show us in jsfiddle.net Commented May 31, 2011 at 13:30
  • what version of jquery are are you using ? Commented May 31, 2011 at 13:32

3 Answers 3

4

Don't check the style attribute. It won't necessarily return the current reality, and it doesn't take into account any styles defined elsewhere.

Use the :hidden filter, or use the css method:

if ($(this).is(':hidden')) {

}

// or

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

}

I'd generally prefer the first syntax, as it takes a little more into account than just the display style.

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

1 Comment

@Pack Glad to help. If an answer has resolved your question, you can mark it as accepted.
0

Use this code instead:

("ul li").each(function() {
  if(($.trim($(this).css("display"))) != "none"){
     //if content
  }else if(($.trim($(this).css("display"))) == "none"){
     //else content
  }
});

Comments

0

Your are comparing an attribut with a property, display is an element property, not an attribute.

Better with something like this:

if( ($.trim($(this).is(':visible') ) {
    // it's visible, do something
}
else { // no need for second condition, we *know* it's not visible!
    // it's not visible so do something else

}

1 Comment

If you call $.trim on a boolean, it will always return a truthy string. $.trim(false) is "false".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.