Nth child not bodyworker

I am trying to draw a 6x6 grid with divs, but when I create them with javascript and css, it doesn't display as expected.

CSS

div{
    width:30px;
    height:30px;
    margin:0px;
    border:1px solid black;
    float:left;
}
div:nth-child(6n+1){
    clear:both;
}

      

JavaScript:

for(var i=0; i<36; i++){
    document.body.appendChild(document.createElement('div'));
}

      

https://jsfiddle.net/kqzhorq0/

The link above shows what I see in the browser.

But, when I select the onload or onDomReady options in the jsfiddle, the grid is displayed as expected.

How can I get the grid to display correctly using onload or onDomReady, and why is it not displaying correctly without it?

+3


source to share


2 answers


If you can put your divs in a container and specify which selectors to target from the container, your code will work.

Here's a working snippet:



for(var i=0; i<36; i++){
    document.getElementById("foo").appendChild(document.createElement('div'));
}
      

#foo div{
  width:30px;
  height:30px;
  margin:0px;
  border:1px solid black;
  float:left;
}

#foo div:nth-child(6n+1){
  clear:both;
}
      

<div id="foo"></div>
      

Run code


I also created an interactive demo nth-child to help explain it further: http://xengravity.com/demo/nth-child/

+3


source


The problem is here, the first child of the body in the fiddle is the script element. You can view the html of the results pane to see the script element.

nth-child will consider all elements when using index to find an element, but using nth-of-type you can search for a specific type.

One option is to use the: nth-of-type selector as shown below

div {
    width:30px;
    height:30px;
    margin:0px;
    border:1px solid black;
    float:left;
}
div:nth-of-type(6n+1) {
    clear:both;
}

      

Demo: Fiddle


Another is to insert a div before the script like

for (var i = 0; i < 36; i++) {
    document.body.insertBefore(document.createElement('div'), document.body.firstChild);
}

      



Demo: Fiddle


But the best solution would be to use a custom container element instead of the body element

var ct = document.getElementById('container');
for (var i = 0; i < 36; i++) {
    ct.appendChild(document.createElement('div'));
}

      

then

#container > div {
    width:30px;
    height:30px;
    margin:0px;
    border:1px solid black;
    float:left;
}
#container div:nth-child(6n+1) {
    clear:both;
}

      

Demo: Fiddle

+1


source







All Articles