0

Apologies in advance... this seems so straightforward but it's as iff my append in the for loop acts as an html method and overwrites the inner html.

$(function () {
    var wrapper = $('<div />', {
        class: 'row'
    }),
    button = $('<div />', {
        class: 'column'
    }),
    buttons = [];
    for (var i = 0; i < 2; i++) {
        var btn = (i % 2)? button.html(i + 1) : button.addClass('last').html(i + 1);
        buttons.push(btn);
        if (i % 2) {
            console.log('buttons', buttons);
            $('.container').append(wrapper.append(buttons));
            console.log('wrapper', wrapper);
            console.log('container', $('.container'));
            buttons = [];
        }
    }
});

Fiddle Here

1
  • What is your issue? Question's title and text look unclear for me. Commented Aug 28, 2014 at 5:45

1 Answer 1

3

when you a object created outside in a loop to add to multiple elements, you need to clone them else you will be just replacing the element from one location to another

$(function () {
    var wrapper = $('<div />', {
        class: 'row'
    }),
        button = $('<div />', {
            class: 'column'
        }),
        btn, wr;
    for (var i = 0; i < 5; i++) {
        btn = button.clone().html(i + 1);
        if (i % 2 == 0) {
            wr = wrapper.clone().appendTo('.container');
            btn.addClass('last')
        }
        wr.append(btn)
    }
});

Demo: Fiddle

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.