54

I would like to create a DOM node, set the 'id' attribute and then append it to 'body'. The following seems not to work because jQuery doesn't see my template as an object:

var template = "<li><div class='bar'>bla</div></li>";
template.find('li').attr('id','1234');
$(body).append(template);

How can I tell jQuery to treat this as an object so find() works on it?

KatieK
  • 13,586
  • 17
  • 76
  • 90
bart
  • 14,958
  • 21
  • 75
  • 105
  • it doesn't work because you are applying find within the dom element you created. In this case you are trying to find `li`underneath `li`, however there is only a `div` and text `bla`. Try something like this to understand what happens `var template=$("
  • bla
")` – stryba Aug 30 '15 at 18:23