4

Is there an alternative for targeting elements using nth-child() for older IE browsers?

Javascript (non-jquery) would suffice as well.

EDIT: Given additional libraries cannot be added to the page.

Anthony Miller
  • 15,101
  • 28
  • 69
  • 98

4 Answers4

16

it sucks a little, but you can

ul > li {} /* first-child, overwritten by below */
ul > li + li {} /* second-child, overwritten by below, etc */
ul > li + li + li {}
ul > li + li + li + li {}

Repeat as necessary.

WraithKenny
  • 1,001
  • 13
  • 15
6

You can use jQuery's :nth-child() selector;

$("li:nth-child(even)") // target even li's
$("li:nth-child(odd)") // target odd li's
$("li:nth-child(5n)") // target the fifth li
Andres I Perez
  • 75,075
  • 21
  • 157
  • 138
  • In case of an absence of jquery, is there a plain javascript solution? – Anthony Miller Jan 04 '12 at 20:29
  • there are no :nth-child implementation in plain javascript, what you can do is in case there is no jQuery support is get creative with css, such as [this](http://abouthalf.com/2011/07/06/poor-mans-nth-child-selector-for-ie-7-and-8/) case or [this](http://www.pbdh.com/open-house/entry/poor-mans-nth-type] other. Modern solutions for older browsers are hard to come by and rely on hacks to work and every case is different so one true solution you're probably not going to find. – Andres I Perez Jan 04 '12 at 20:49
  • poor man's nth-child will have to suffice for now. Thanks for the link =D – Anthony Miller Jan 06 '12 at 22:43
4

There is Selectivizr: http://selectivizr.com/

:nth-child is supported in every javascript framework that works with it, including jQuery.

The big advantage with using this is that it reads directly from your CSS files rather than having to write additional javascript (it's unobtrusive). You can simply use the advanced selectors as normal.

Wesley Murch
  • 101,186
  • 37
  • 194
  • 228
  • This sounds pretty cool. I'll keep this as a reference for my own sites. – Anthony Miller Jan 04 '12 at 20:36
  • I always just end up using CSS2 :( I have to support IE7, and none of the solutions I know of that are out there can cope well with new elements that are added to the DOM (think AJAX), after the js patch loads and parses the CSS. Even the jquery solution in the other answer can't deal with this unless you use the livequery plugin or something similar to call those functions again when the page is updated. If you aren't adding new elements to the page, it's not an issue, but it's a huge deal-breaker for me. – Wesley Murch Jan 04 '12 at 20:39
1

You can use the IE9.js polyfill: http://ie7-js.googlecode.com/svn/test/index.html.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • 3
    IEX.js is pretty powerful, but it's a *beast*. I've actually had more problems come from using it. – Wesley Murch Jan 04 '12 at 20:35
  • 1
    IEX.js stopped Respond.js from working. So watch out if your building a responsive site that need to support IE8 and below. – Dil A Feb 21 '14 at 11:24