0
function test() {
    var a = $('<p>'),
        b = $('<div>')

    for (var i = 0; i < 10; i++) {
        b.append(a)
    }

    console.log(b)
}

This function creates 1 element with 1

element inside it. Why there is not 10

elements? How can I append as many

element as many times loop goes?

4 Answers 4

1

append() function move your object. You should use clone() before append()

function test() {
    var a = $('<p>'),
        b = $('<div>')

    for (var i = 0; i < 10; i++) {
        b.append(a.clone())
    }

    console.log(b)
}
Sign up to request clarification or add additional context in comments.

Comments

1

When you append an element, as it has only one parent, you remove it from its ancient location.

So you must clone it here before appending :

for (var i = 0; i < 10; i++) {
    b.append(a.clone())
}

Comments

0

Try this:

for (var i = 0; i < 10; i++) {
    b = b.append(a);
}

Comments

0

You need to create a new element each time through the loop, not reuse the same element, since an element can only be in one place in the DOM.

for (var i = 0; i < 10; i++) {
    b.append($("<p>"));
}

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.