Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nth-child not working on dynamically generated DOM

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);
like image 906
thesonglessbird Avatar asked Feb 19 '14 14:02

thesonglessbird


People also ask

How do you target the nth child in SCSS?

Writing Complex :nth-child() Selectors It works exactly the same as :nth-child except that it starts from the end of the parent. For example, you can select the first three children of a parent by using the selector :nth-child(-n + 3) . You can use :nth-last-child(-n + 3) to select the last three.

How do I access my nth child?

The :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.

When can you use Nth child?

The :nth-child selector allows you to select one or more elements based on their source order, according to a formula. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling elements.


1 Answers

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.

like image 57
jAndy Avatar answered Sep 26 '22 10:09

jAndy