Reputation: 1852
I want to create HTML like this
<div id="positional">
<div>
<div>
<label for='azimuth'>Azimuth</label>
</div>
<div>
<input id='azimuth'>
</div>
</div>
</div>
I was trying to use this, but I can't get it to work, can you help?
$("<div><input id='azimuth'></div>")
.insertAfter("<div><label for='azimuth'>Azimuth</label></div>")
.wrap("<div></div>")
.appendTo("#positional");
Assume <div id="Positional">
has already been created. Thanks, I'm pulling my hair out.
EDIT: I know I could just hand insert the HTML in one unreadable blob, but I'm trying to do it step by step and understand the problem. In this the div containing the label doesn't appear.
EDIT2: Seriously, if anyone could explain why this doesn't work, I would be very grateful.
Upvotes: 1
Views: 264
Reputation: 92274
The $.wrap
, $.after
, $.appendTo
don't work with in memory nodes. See JQuery: Build HTML in 'memory' rather than DOM
Put your starting node into the DOM before calling those methods http://jsfiddle.net/j824yyng/2/
$("<div><label for='azimuth'>Azimuth</label></div>")
.appendTo("#positional")
.wrap("<div></div>")
.after("<div><input id='azimuth'></div>");
As others have pointed out, this is not very readable. It may be a good lesson in jQuery
but I would hate you if I had to modify the code above instead of the straight forward version.
Upvotes: 1
Reputation: 2768
$('#positional').html('<div><div><label for="azimuth">Azimuth</label></div><div><input id="azimuth"></div></div>');
Upvotes: 1
Reputation: 61063
Unless there's more to the story than what you've mentioned, this should do fine.
var myHtml = '<div>'
+ '<div>'
+ ' <label for="azimuth">Azimuth</label>'
+ '</div>'
+ '<div>'
+ ' <input id="azimuth">'
+ '</div>'
+ '</div>';
$('#positional').html(myHtml);
Upvotes: 5