0

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.

1 Answer 1

1

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
    }

  }
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.