Jasper de Vries
Jasper de Vries

Reputation: 20178

Forcing to re-apply a style sheet in IE

Consider this HTML:

<ul>
<li>first</li>
<li>second</li>
<li>third</li>
</ul>

This CSS:

li:first-child { background: yellow; }

And this Javascript (jQuery):

$("ul").append($("li:first-child"));

http://fiddle.jshell.net/Xtuaf/

Apparently in Internet Explorer (8) :first-child breaks when the DOM has changed. I wrote a workaround for this problem in Javascript (doing styling there; z-indexes in my case). It's an ugly quick fix that I want to get rid of. A better solution would be forcing to re-apply the style sheet when the DOM changes. Can this be done? Or is there an other solution to this problem?

Upvotes: 3

Views: 724

Answers (2)

John Culviner
John Culviner

Reputation: 22954

One way to reliably cause a reflow of the entire DOM is to quick add and remove an arbitrary class from the body element.

$('body').addClass('foo').removeClass('foo');

Upvotes: 1

Rob W
Rob W

Reputation: 348992

In Internet Explorer, a reflow can be triggered by setting the class name:

$("ul").append($("li:first-child")).addClass('x').removeClass('x');

Or just (demo: http://fiddle.jshell.net/Xtuaf/1/):

$("ul").append($("li:first-child"))[0].className += '';

Upvotes: 3

Related Questions