4

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.

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Karric
  • 1,415
  • 2
  • 19
  • 32
  • why don't you split it into two functions call of jquery? `$(".Target").append("
    ");$("p:even").clone().appendTo(".new"); `
    – Jacky Shek Apr 05 '16 at 02:23
  • Is there a reason that you want to take this approach, rather than first creating the element to which you want to append the cloned content? – David Thomas Apr 05 '16 at 07:29

2 Answers2

1

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>').

Ouroborus
  • 16,237
  • 4
  • 39
  • 62
0

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>
zer00ne
  • 41,936
  • 6
  • 41
  • 68