chipit24
chipit24

Reputation: 6987

How to get Element from Node

From my understanding, document.querySelector returns a Node object. I can then call appendChild on this object.

I execute the following code to append a bunch of divs to my container div:

var container = document.querySelector('.container');
for (var i = 0; i < 400; i++) {
  var block = document.createElement('div');
  block.className = 'block';
  container.appendChild(block);
}

And end up with the following structure:

<div class="container">
  <div class="block"></div>
  <div class="block"></div>
  ...
  <div class="block"></div>
</div>

How can I loop through each element in my container div and add a new class to it using my existing container variable?

I have tried this:

...
container.childNodes[i].className = 'myClass';

It seems I need to access the Element object of the child Node, but I'm not sure how to do this.

Upvotes: 4

Views: 12760

Answers (2)

chipit24
chipit24

Reputation: 6987

To add classes to the elements in the container variable, I used the following code:

container.children[i].className = 'myClass';

I had to use children instead of childNodes. You can see the context in which this code was used here: http://codepen.io/robkom/pen/RWmodz.

Upvotes: 0

cmd430
cmd430

Reputation: 102

Can you not just add it when you create the divs ?

var container = document.querySelector('.container');
for (var i = 0; i < 400; i++) {
  var block = document.createElement('div');
  block.className = 'block myClass';
  container.appendChild(block);
}

Upvotes: 0

Related Questions