wyc
wyc

Reputation: 55273

empty().append() appending last item in loop

I'm doing the following:

$('.document-content').on('input', function() {
  var headers;
  headers = $('.document-content > h2').each(function() {
    var headerId, headerText;
    headerId = $(this).attr('id');
    headerText = $(this).text();
    $('.document-outline').empty().append("<h2><a href='#" + headerId + "'>" + headerText + "</h2>");
  });
});

In order to avoid duplication, I added empty() but now only the last item in the each loop is being appended to .document-outline.

How can I fix this?

Upvotes: 0

Views: 98

Answers (3)

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

Empty it outside loop otherwise you will end with appending last elements only as everything before it will get emptied

$('.document-content').on('input', function() {
  var headers, 
  var outlineDoc = $('.document-outline').empty()
  headers = $('.document-content > h2').each(function() {
    var headerId, headerText;
    headerId = $(this).attr('id');
    headerText = $(this).text();
    $(outlineDoc).append("<h2><a href='#" + headerId + "'>" + headerText + "</h2>");
  });
});

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

You need to empty() the containing element outside of the loop, otherwise it is being cleared on each iteration.

$('.document-content').on('input', function() {
    var $headers = $('.document-content > h2'), 
        $outline = $('.document-outline').empty()

    $headers.each(function() {
        var headerId = $(this).attr('id'),
            headerText = $(this).text();
        $outline.append("<h2><a href='#" + headerId + "'>" + headerText + "</h2>");
    });
});

Note that I shortened the logic slightly by setting the values as the variables are declared.

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

You need to empty it before the loop, else before adding any item you are removing the previous contents meaning all the previous items are removed thus only the last item in the loop is kept

$('.document-content').on('input', function () {
     var $ct = $('.document-outline').empty();
    var headers;
    headers = $('.document-content > h2').each(function () {
        var headerId, headerText;
        headerId = $(this).attr('id');
        headerText = $(this).text();
        $ct.append("<h2><a href='#" + headerId + "'>" + headerText + "</h2>");
    });
});

Upvotes: 2

Related Questions