Reputation: 3
I have created a simple to do list which takes the value of the input and places it in a div and attaches some classes to them, everything works fine but how do I fix the for loop and make it work everytime and adds multiple divs under eachother instead of changing the existing one. Here's my code:
let dynamicList = document.querySelector("#dynamic-list"),
dynamicDiv = document.createElement("div"),
dynamicClass = document.querySelector(".dynamic"),
circle = document.querySelector(".circle"),
paragraphTest = document.createElement("p"),
circleTest = document.createElement("div");
input.addEventListener("keypress", function(e){
value = input.value
if(e.key == "Enter"){
for(i=0; i<=dynamicList.children.length; i++){
dynamicList.insertBefore(dynamicDiv, dynamicClass.nextSibling)
let sibling = dynamicClass.nextSibling;
sibling.classList.add("dynamic")
sibling.appendChild(circleTest)
circleTest.classList.add("circle")
sibling.appendChild(paragraphTest)
paragraphTest.innerHTML = input.value
}
})
<div id="dynamic-list">
<div class="dynamic"><div class="circle"></div><p class="paragraph">some dummy text/p></div>
</div>
Here's what I mean:
https://i.sstatic.net/aKIw5.jpg
That's what happens when I add text, it works perfectly. But when I add another text it overrides the first one instead of adding another div.
Upvotes: 0
Views: 172
Reputation: 1160
You should use createElement method every time you want to create that element. by just using it once, it will create only one, so if you change its property, you are editing the first element (the only one that has been created already).
so the code should be written like this :
let dynamicList = document.querySelector("#dynamic-list"),
dynamicClass = document.querySelector(".dynamic"),
circle = document.querySelector(".circle");
input.addEventListener("keypress", function(e) {
value = input.value
if (e.key == "Enter") {
const paragraphTest = document.createElement("p"),
dynamicDiv = document.createElement("div"),
circleTest = document.createElement("div");
for (i = 0; i <= dynamicList.children.length; i++) {
dynamicList.insertBefore(dynamicDiv, dynamicClass.nextSibling)
let sibling = dynamicClass.nextSibling;
sibling.classList.add("dynamic")
sibling.appendChild(circleTest)
circleTest.classList.add("circle")
sibling.appendChild(paragraphTest)
paragraphTest.innerHTML = input.value
}
}
})
Upvotes: 1