Hi,

This will do the job, but it's ugly, so how to do this more elegant?

$('ul').prepend('<li></li><li></li><li></li><li></li><li></li>');
$('ul').append('<li></li><li></li><li></li><li></li><li></li>');

Thanks in advance!

Recommended Answers

All 6 Replies

By elegant do you mean simpler? Less code? More didact? More Efficient?
Elegant code it's a very personal concept i think.
For me, elegant code it's a set of well structured and dynamic functionalities.
That's said, here's a more dynamic function.

var _add = function($el, num, method) {
    var html, i;
    for(i=0;i<num;i++) {
        html += '<li></li>';
    }

    $el[method].call($el, html);
};  

_add($('ul'), 5, 'prepend');
_add($('ul'), 5, 'append');

Yeah 'elegant' was a bad way to describe what I was looking for I guess :)

Nonetheless, I was looking for something more programmatical (another weird way to describe it), kind of like you wrote here now... haha
This is where I fall short... I know how to traverse the DOM with jQuery to select the elements I want to select and do simple functions, but when it comes to real programming I'm a total noob :)

Thanks for this snippet and I will try to understand what is going on in there!

It's quite simple:

// $el = jquery element to add the itens
// num = number of elements to add
// method = method used to add elements
var _add = function($el, num, method) {
    var 
        html // hold the html string
        , i // counter;

    // Adds the elements in the html string
    for(i=0;i<num;i++) {
        html += '<li></li>';
    }
    // Adds the html string to the jquery element
    $el[method].call($el, html);

    // it could be writen simpler as
    if ( method == 'append' ) {
        $el.append(html);
    }
    else if ( method == 'prepend' ) {
        $el.prepend(html);
    }

};  

Thanks for the explanation and for a second alternative for the last bit. I will try that too.

I implemented the first code snippet of yours by the way and it does append and prepend the li's, but it adds also dynamically twice, before the first of the five li's, a text node "undefined"

"undefined"
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>

So I'm not sure why that happens.

Oh, sorry, my bad. You have to set html to empty;

var html = '', i;

Aha... that was indeed needed... "undefined" is gone now.
Thanks for this and although the snippet looks more terrifying now then what I had, I assume it's better like this :)
for loop, counter, num, method... they're all new to me.

Cheers!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.