cmp
cmp

Reputation: 452

Append many divs inside of a div

In order to animate images in - I need to add many divs using Javascript over the image where at present the markup is

<div class="js-img-in">
 <figure><img src="test.jpg"></figure>
</div>

To eventually compile to

<div class="js-img-in">
 <div class="js-anim-img-in"></div>
 <div class="js-anim-img-in"></div>
 <div class="js-anim-img-in"></div>
 <div class="js-anim-img-in"></div>
 <div class="js-anim-img-in"></div>
 <figure><img src="test.jpg"></figure>
</div>

My code at the moment returns appendChild is not a function.

const imageAnimIn = () => {
  const images = document.querySelectorAll(".js-img-in");
  for (var x = 0; x < 5; x++) {
    var imageOverDivs = document.createElement('div');
    imageOverDivs.className = "js-anim-img-in";
    images.appendChild(imageOverDivs);
  }
}

This error took me to this S.O article. createTextNode here, however, will not help me as I am adding an element node, not text.

Will querySelectorAll not work in this instance?

Upvotes: 1

Views: 1005

Answers (2)

symlink
symlink

Reputation: 12208

You want querySelector(), not querySelectorAll(). Then you want Node.insertBefore(), and pass in the figure element as the second argument.

const imageAnimIn = () => {
  const image = document.querySelector(".js-img-in")
  const fig = document.querySelector(".js-img-in > figure")
  for (var x = 0; x < 5; x++) {
    var imageOverDivs = document.createElement('div');
    imageOverDivs.className = "js-anim-img-in";
    image.insertBefore(imageOverDivs, fig)
  }
}

imageAnimIn()
.js-anim-img-in::after{
   content: "New Div"
}
<div class="js-img-in">
 <figure><img src="http://placekitten.com/100/100"></figure>
</div>

<!--<div class="js-img-in">
 <div class="js-anim-img-in"></div>
 <div class="js-anim-img-in"></div>
 <div class="js-anim-img-in"></div>
 <div class="js-anim-img-in"></div>
 <div class="js-anim-img-in"></div>
 <figure><img src="test.jpg"></figure>
</div>-->

Upvotes: 2

Sunny Patel
Sunny Patel

Reputation: 8077

Did you mean to loop through images.length, and use the image position? Because the result of document.querySelectorAll is a NodeList, not just a single node.

const imageAnimIn = () => {
  const images = document.querySelectorAll(".js-img-in");
  for (var x = 0; x < images.length; x++) {        // Loop through each result
    for (var _ = 0; _ < 5; _++) {                  // Updated to disregard variable
      var imageOverDivs = document.createElement('div');
      imageOverDivs.className = "js-anim-img-in";
      images[x].appendChild(imageOverDivs);        // Added [x]
    }
  }
}

Upvotes: 1

Related Questions