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>