Control Freak
Control Freak

Reputation: 13243

Why isn't this appendTo working?

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

Answers (3)

Adil
Adil

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()

Live Demo

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

Joe Enos
Joe Enos

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

Kiran
Kiran

Reputation: 20293

Use jQuery .wrap(). Try this:

var $sel = $("<select></select>");
$sel.append("<option>1</option");
$sel.wrap("<div></div>").parent().insertAfter("#mydiv");

DEMO

Upvotes: 2

Related Questions