Maybe I'm just missing something simple, but it doesn't seem like anyone else has asked this question anywhere. I'm trying to create a new section of HTML nodes and would like to be able to do it all in a concise and chained manner.
Basically I'd like to do something like this:
var options = {
buttons: {
'New': function() { /* Do some work*/ }
'Edit': function() { /* Do some work*/ }
// etc.
}
};
$( '#container' ).append(
$( '<div />', { 'class': 'table' } ).append(
$( '<div />', { 'class': 'row' } ).append( function() {
$.each(options.buttons, function(key, value) {
$( '<button />', { text: key } ).click(value);
// Somehow return this object so the append can work with it
});
})
)
);
What I'd like to have happen is to have it so that the each function is able to return a button element with the click handler associated with it for each button in the options object. There are other options in for which I'd like to do the same thing, but I can't figure out the syntax.
I know this can be done with the reverse having the $.each function contain the .append() function, but this seems to have a performance hit for long collections. Anyone have any suggestions?
Edit: I should note that I have tried the following as a work around, but I have to insert a new unneeded element.
$( '<div />', { 'class': 'row' } ).append( function() {
var div = $( '<div />', { } );
$.each(options.buttons, function(key, value) {
div.append( $( '<button />', { text: key } ).click(value) );
});
return div;
})
You might want to take a look at
jQuery.map()
.This takes an array and returns an array. Thus, you can return your array of DOM elements for
.append
to consume.Use
$.map
instead of$.each
:JSFIDDLE DEMO
Note that you can shorten it a bit if you get rid of the function of one of the appends:
JSFIDDLE DEMO