1

Well, the result I want to get is my div element should have the same numbers of p elements as the array.

In order to do this, I tried using a for loop but it just create one p element, so I didn't work.

Anyone have idea how to do this? (I'm just learning js).

const diccionario = () => {
    var dama = ["bird:pajaro", "car:carro", "house:csa", "camis"];

    document.getElementById("dic").addEventListener("click", () => {
        var pes = document.createElement("p");
        for(var i = 0;  i < dama.length; i++){
            pes.innerHTML = dama[i];
            document.getElementById("cuadro").appendChild(pes);     
        }
    })
}
1
  • 1
    Move the var pes line 1 line down (inside the for loop) and you are good to go. Commented Mar 12, 2020 at 9:31

1 Answer 1

2

You need to create the element inside the loop. If you create it outside the loop, then when you call appendChild, it will get removed from wherever it was previously in the DOM:

const diccionario = () => {
    var dama = ["bird:pajaro", "car:carro", "house:csa", "camis"];

    document.getElementById("dic").addEventListener("click", () => {
        for(var i = 0;  i < dama.length; i++){
            var pes = document.createElement("p"); // <----------------
            pes.innerHTML = dama[i];
            document.getElementById("cuadro").appendChild(pes);     
        }
    })
}

appendChild doesn't create a copy of the existing element - rather, it just appends the existing element.

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

3 Comments

If someone create element outside and clone it inside using cloneNode rather than using createElement will it increase performance?
I tried it, but I don't see a noticeable difference.
@Kenny When an answer solves your problem, you may consider marking it as Accepted (check the checkbox on the left) to indicate that the issue is resolved :)

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.