Skip to content
Advertisement

Append inside a child difficulties

This is my current situation. I got one parent called “box” which got 15 childrens inside called item. Then I got a loop where I append some text that should be inside the children div. If I append it directly inside the children the code gets messed up and I get the 15 things I want to inside in each children in all of them. So I have to append inside my parent. However I found this smart function called appendChild which at first was not a function because I wanted to insert a string if I understood correctly… Then I found this solution In how to make it a function but in the end it still doesn’t gets placed in my children div. How am I supposed to do in my case? I guess

This is my code at the moment;

<div id = "box">
  <div class = "item"></div> X15
</div>
$.each() {
    var element = document.getElementById("result");
    element.appendChild("coolText");
});

Got this error last check: Error: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'

Advertisement

Answer

You can use a forEach to iterate the items and append the content one by one. Like this:

const box = document.getElementById('box');
const items = document.querySelectorAll('.item');

items.forEach(item => {
  let content = document.createTextNode("text");
  item.append(content);
});
<div id = "box">
  <div class = "item"></div>
  <div class = "item"></div>
  <div class = "item"></div>
  <div class = "item"></div>
  <div class = "item"></div>
  <div class = "item"></div>
  <div class = "item"></div>
  <div class = "item"></div>
  <div class = "item"></div>
  <div class = "item"></div>
  <div class = "item"></div>
  <div class = "item"></div>
  <div class = "item"></div>
  <div class = "item"></div>
  <div class = "item"></div>
</div>

Or if you want to use Jquey

const box = document.getElementById('box');
const items = document.querySelectorAll('.item');

$.each(items, (i, item) => {
  let content = document.createTextNode("text");
  item.append(content);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id = "box">
  <div class = "item"></div>
  <div class = "item"></div>
  <div class = "item"></div>
  <div class = "item"></div>
  <div class = "item"></div>
  <div class = "item"></div>
  <div class = "item"></div>
  <div class = "item"></div>
  <div class = "item"></div>
  <div class = "item"></div>
  <div class = "item"></div>
  <div class = "item"></div>
  <div class = "item"></div>
  <div class = "item"></div>
  <div class = "item"></div>
</div>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement