1

I am not sure what is the correct way of writing the code, or is it even a possible jquery format.

I have

for(i=0; i<10; i++) {
  var inner = $('<div/>', {text: 'it works'});
  var x = ' xyz ';

  var row = $('<div/>', {
    id: 'foo',
    'class': 'abc',
    html: 'test'+ x + inner.text(),
    css: {'padding-left': '5px'}
  });

  row.appendTo('body');
}

The output is test xyz [object Object]

What is the correct syntax for displaying the inner variable so that the correct output would be 'test xyz it works' ?

I know that it would work with using inner.appendTo(row)

A secondary question: If I could get the code to work, what would be faster? appendTo or defining the html with a variable.

TIA

Josh
  • 2,158
  • 18
  • 22
Jamex
  • 1,164
  • 5
  • 22
  • 34
  • Try `html: 'test' + x + inner.html()` or `html: 'test' + x + inner.text()`. This is a total shot in the dark, just fyi. :) – Elliot Bonneville Mar 09 '12 at 04:12
  • Awesome, I'll post it as an answer for you to accept. – Elliot Bonneville Mar 09 '12 at 04:23
  • Follow up 'answer' for my secondary question --> apparently, if I use html: inner.html() , it will append only the html contents of the 'inner' div, it will ignore inner's css definitions. I am not sure which is faster, but it seems like this method will require specific declarations of all the properties. – Jamex Mar 09 '12 at 05:22

2 Answers2

1

You'll want html: 'test' + x + inner.html(); or html: 'test' + x + inner.text();

Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123
  • Thanks Elliot, by any chance that you know if this method is faster than the append method? – Jamex Mar 09 '12 at 04:45
  • Elliot, take a look at my follow up comment. – Jamex Mar 09 '12 at 05:23
  • Hi Josh, I don't quite follow the test results. The chart shows that Elliot's method has more ops/sec (higher is better). But the table above that says that Elliot's method is SLOWER. I don't know if the code for that tool is reversed or that I missed something. – Jamex Mar 09 '12 at 05:37
1

Did you want to move the inner div into the containing (row) div? If so, you'd want to do the following:

$(function() {
    for(i=0; i<10; i++) {
    var inner = $('<div/>', {
    text: 'it works'
    });

    var x = ' xyz ';

    var row = $('<div/>', {
    id: 'foo',
    'class': 'abc',
    html: 'test'+ x,
    css: {  
    'padding-left': '5px'
        }
    }).append(inner).appendTo('body');

    }//end for
});
chrisn
  • 2,095
  • 15
  • 20
  • Thanks Chris, see Elliot's answer. Your append method works too, I was just wonder how I could to it the other way. BTW, do you know if append is faster for jquery to execute than Elliot's method? – Jamex Mar 09 '12 at 04:43