Karric
Karric

Reputation: 1565

How to appendTo() a new element

I was wondering if it's possible to create a new element as the target when using appendTo(). I could not find anything online.

For example:

$("p:even").clone().appendTo( **NEW: $(".Target").append("<div class='new'>"**) );

The point being to add the collection of objects to a new div within another element.

Upvotes: 4

Views: 1609

Answers (2)

zer00ne
zer00ne

Reputation: 43880

There's so many ways to create an element on the fly in jQuery. I try to remember it like this: If ain't there, but if you say it's there, it's there now. The jQuery Object $() will parse HTML strings:

$('<main id="alpha" class="prime" name="first">NUMBER ONE</main>');

Store a created element in a variable (a var with $ is just a way to differentiate between a normal Object and a jQuery Object):

var $ele = $('<div/>'); 

Although created, it is not on the DOM until it is appended after or during creation like this:

$('<div class="new"></div>').appendTo('body')[0];

Refer to this page for more details.

var $clones = $('p:nth-child(2n+1)').clone();
var $new = $('<div class="new">NEW</div>').appendTo('.Target');
$clones.appendTo($new);
p:nth-child(odd) {
  background: rgba(0, 0, 255, .4);
}
p:nth-child(even) {
  background: rgba(255, 0, 0, .4);
}
.Target {
  border: 3px dashed blue;
}
.new {
  border: 2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
<p>10</p>

<section class="Target">TARGET</section>

Upvotes: 0

Ouroborus
Ouroborus

Reputation: 16875

Not in that way. This does what you're asking but seems convoluted:

$("p:even").clone().appendTo($("<div class='new'></div>").appendTo($(".Target")));

Instead, you should go for clarity, such as:

var newDiv = $("<div class='new'></div>");
var pEven = $("p:even");
var target = $(".Target");
newDiv.append(pEven.clone());
target.append(newDiv);

It occurs to me that I may have misinterpreted what you were asking. If you just wanted to create a new element such that you ended up with a jQuery object that you could use appendTo on, it goes like $('<div></div>').

Upvotes: 1

Related Questions