0

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!

Edited by gentlemedia

2
Contributors
6
Replies
14
Views
2 Years
Discussion Span
Last Post by gentlemedia
0

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');
0

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!

Edited by gentlemedia

0

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

};  
0

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.

Edited by gentlemedia

0

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!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.