Reputation: 570
I'm having problems using nth-child in my CSS (tried in Chrome and Firefox so far). Parts of the DOM are generated dynamically on the client side using vanilla DOM manipulation methods (document.createElement, document.appendChild etc.)
The CSS I'm using and the generated DOM are below:
CSS:
#loginForm label {
color: #FF0000
}
#loginForm label:nth-child(1) {
color: #8a8a8a;
}
DOM:
<div id="loginForm">
<form>
<label>Label 1</label>
<label>Label 2</label>
</form>
</div>
I've tried putting this HTML and CSS into a JSFiddle and everything is working fine so I can only imagine it's something to do with my DOM manipulation.
I noticed on the MDN page for nth-child that Opera can't handle dynamic insertion of elements, but there's no mention of other browsers. Am I right to assume that no browsers can handle dynamic insertion and nth-child? If so, is there a workaround?
EDIT:
DOM insertion code (the final line uses the target variable that's passed into the function containing the code). Obviously, there's more code to it, but this are the key parts:
var contentHolder = document.createElement("div");
var form = document.createElement("form");
var userLabel = document.createElement("label");
form.appendChild(userLabel);
contentHolder.appendChild(form);
document.getElementById(target).appendChild(contentHolder);
Upvotes: 6
Views: 4149
Reputation: 236202
I guess what you're looking for is the :nth-child(2n+1)
selector.
Example: http://jsfiddle.net/usScP/
You could also more simplify this by using :nth-child(odd)
or :nth-child(even)
. By just using the :nth-child( number )
selector, you specifically only address that index in NodeList order.
Upvotes: 3