2

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.

1 Answer 1

3

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>');
}
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.