HalfWebDev
HalfWebDev

Reputation: 7638

Append items in a for loop- jquery

I am adding a simple toggle button through Javascript. Then I want to add three span tags inside it.

So, I am creating variable of span and trying to append it inside our very own basic FOR loop. Iteration count is 3 times.

Here's my basic code below. Please let me know what has been missing or misplaced that my span tag refuses to append more than once. I checked this in the inspect mode.

Then, I brought up console tab and the value of i was 3. Append is meant to append and NOT replace the element. Right ?

var $navbar_header = $('<div class="navbar-header"></div>');

var $button = $("<button></button>");
var $span = $('<span class="icon-bar"></span>');

for (var i = 0; i < 3; i++) {
   $button.append($span);
 }

$button.addClass('navbar-toggle');
$navbar_header.append($button);
$("#menu").append($navbar_header);

Here's a link to fiddle.

Upvotes: 2

Views: 4011

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382102

The DOM is a tree, where any element points to its parent (see parentNode). An element can have only one location. So when you append an element, you're removing it from its precedent location.

The solution here is either to clone the element:

$button.append($span.clone());

or just to create it in the loop:

for (var i = 0; i < 3; i++) {
    $button.append('<span class="icon-bar"></span>');
}

Upvotes: 3

Related Questions