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

3
  • Try html: 'test' + x + inner.html() or html: 'test' + x + inner.text(). This is a total shot in the dark, just fyi. :) Commented Mar 9, 2012 at 4:12
  • Awesome, I'll post it as an answer for you to accept. Commented Mar 9, 2012 at 4: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. Commented Mar 9, 2012 at 5:22

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Elliot, by any chance that you know if this method is faster than the append method?
Elliot, take a look at my follow up comment.
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.
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
});

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.