1

I am trying to $.append dynamically constructed elements inside a dynamically constructed element inside of a custom plugin:

$('<div/>').append( function(){
    $.each(paramaterObject.rows, function(rowKey, rowValue){
        return $('<div/>')...

but Chrome console gives Object [object Array] has no method 'apply'.

Is it possible to $.append() this way? If not, is there an alternative? Please show me how.

  • just learned a lot from my last 3 questions, but one might want to look here if going down the same road as i was: http://json2html.com/ –  Jun 07 '13 at 23:19

2 Answers2

2

No, you can't return from the iterator -- you have to keep a buffer that you fill, and return the buffer when all iterations are done.

Something in the lines of;

$('<div />').append(function () {

    var buffer = "";
    $.each (parameterObject.rows, function () {
        buffer += "<div />";
    });
    return buffer;

});
Björn
  • 29,019
  • 9
  • 65
  • 81
  • "No, you can't return from the iterator.." i would say returns in iterators are used to tell `.each()` to stop itering. +1 anyway. – Karl-André Gagnon Jun 07 '13 at 14:07
  • @Karl-AndréGagnon, it actually doesn't stop the iterator -- it works as `continue` does in a regular for-loop (just skips the current iteration). – Björn Jun 07 '13 at 14:38
  • Sorry if I missexplained myself. What i meant is that you can use return in each, but it is used to stop the loop (with `return false`). – Karl-André Gagnon Jun 07 '13 at 14:42
1

You can try:

    var parentDiv = $('<div/>');
    $.each(paramaterObject.rows, function(rowKey, rowValue){
        parentDiv.append($('<div/>'));
    });
ysrb
  • 6,693
  • 2
  • 29
  • 30