Haque1
Haque1

Reputation: 593

Outputting numbers 1 to 100 onto a page

I'm new to web development. I need to output all numbers ranging from 1-100, each on a new line. The following code only outputs the last number:

var main = function() {

    for(var i = 1; i <= 100; i++) {
        $(".results").append("<p>").text(i);
    }
};

$(document).ready(main);

While, this does exactly what I want it to:

var main = function() {
    var $content;

    for(var i = 1; i <= 100; i++) {
        $content = $("<p>").text(i);
        $(".results").append($content);
    }
};

$(document).ready(main);

Why does the second solution work but not the first?

Upvotes: 1

Views: 107

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337666

The issue with the first is that append() returns the parent element (the .results element) not the p which was appended to it. You are therefore updating the text property of .results on each iteration.

Note also that append() is a relatively expensive operation in terms of performance, so you can improve execution speed by rearranging your logic to only append once:

var main = function() {
    var content = '';
    for (var i = 1; i <= 100; i++) {
        content += '<p>' + i + '</p>';
    }
    $(".results").append(content);
};

Upvotes: 5

Related Questions