JS_ how to create and appendChildren inside each other. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

JS_ how to create and appendChildren inside each other.

Start with: <div class = "a"> </div> Then in JS, create n more elements (5) with the class ‘a’ then nest each element inside each other. Result should be something like: <div class = ‘a’> <div class = ‘a’> <div class = ‘a’> <div class = ‘a’> <div class = ‘a’> ... </div> </div> </div> </div> </div> So one of those children is the leader of all, then there is second place... nesting each other. Started code: https://code.sololearn.com/WiJamfrphp4S/?ref=app

12th May 2020, 8:23 AM
Ginfio
Ginfio - avatar
4 Answers
+ 5
This is the solution i came up with, what it does is it keeps track of last appended child and appends a new child inside of it. let lastAppended = null; window.onload = () =>{ parent = document.querySelector('.a'); for(let i = 0; i < 5; i++) { let newChild = document.createElement('div'); newChild.classList.add('a'); if (lastAppended == null) { parent.appendChild(newChild); } else { lastAppended.appendChild(newChild); } lastAppended = newChild; } } after a little styling modifications https://code.sololearn.com/WirdxeJ4v3zR/?ref=app
12th May 2020, 8:52 AM
Raj Chhatrala
Raj Chhatrala - avatar
12th May 2020, 8:53 AM
Calviղ
Calviղ - avatar
12th May 2020, 1:28 PM
ODLNT
ODLNT - avatar
+ 2
O, wow_ Thanks you, all.
12th May 2020, 4:51 PM
Ginfio
Ginfio - avatar