Reputation: 13243
JS:
var $sel = $("<select></select>");
$sel.append("<option>1</option");
var $sel = $sel.appendTo("<div></div>");
$sel.insertAfter("#mydiv");
HTML:
<div id=mydiv></div>
This only appends the select box, but not wrapped in the div. I would like the select wrapped by another div appended to #mydiv. I tried:
$sel.appendTo("<div></div>").insertAfter("#mydiv");
but that doesn't work either
Upvotes: 1
Views: 104
Reputation: 148180
Your code is fine with appendTo
and no need to use wrap
, but you are inserting the wrong element i.e. the select instead of the div that has wrapped the select. You need to use $sel.parent()
with insertAfter()
var $sel = $("<select></select>");
$sel.append("<option>1</option");
var $sel = $sel.appendTo("<div></div>");
$sel.parent().insertAfter("#mydiv"); //Insert the parent of select instead of select.
Upvotes: 1
Reputation: 40431
$sel
is just the select box, not the thing that wraps it. If you want that too, you can put that in a variable:
var $div = $("<div></div>");
$div.append($sel).insertAfter("#mydiv");
Or of course there are a dozen other ways to do it, but this keeps everything nice and organized.
Upvotes: 3