Problem
<div class='element1'></div>
<div class='element2'></div>
"How to add these two divs into the div with class container?"
Solution
The jQuery selector that will collect any instances of .element1
and .element2
classes is:
$(".element1, .element2")
A quick breakdown of the syntax:
$( // Begin jQuery Object
" // Begin Selector
. // Begin ClassName
element1 // Full ClassName
, // AND
. // Begin ClassName
element2 // Full ClassName
" // end Selector
) // end jQuery Object
Finally, we need to insert this jQuery Collection inside div.container
:
<!--//B00~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-->
/* B00 EXAMPLE */
$(".container").append($(".element1, .element2"));
In JavaScript there's many ways to insert elements within other elements and jQuery has all JavaScript capabilities as well of its own. The previous Example B00 (located above,) uses the most commonly used jQuery method for DOM manipulation: append().
7 Examples
First 3 Examples: C01, C23, & C45
- The first two Examples each offer an alternative jQuery method to
accomplish the same objective. See C01
prependTo()
and
C23 wrapInner()
.
The third Example pertains more to your need to plan your coding.
I'm well aware of users that cannot alter their code due to
circumstances such as a restrictive (more like limited) CMS, or
propriety code your employer forbids anyone to alter. More often
than not, it could be that the user isn't comfortable using script
or the user has enough knowledge to assume some proposed solution
will not work because it doesn't do what the user thinks he or she
needs (even when a solution actually resolves the problem.) Not
saying that you are the latter type of user, but I smell a XY
Problem. Hence the third Example C45, involves adding a
Common Class
to .E4
(.element1
in OP code) and .E5
(.element2
in OP code):
/* EXAMPLE C45 /
// Here 2 divs with similar classes get a *common class* to hook into.
|| The common class in this Example is `.E` in OP code it could be
|| `.elements`. By implementing common classes, we could group elements
|| semantically, logically, alphabetically, categorically, anything is
|| better than dealing with a thousand unique variations of a class and
|| having to sort them out all the time.
*/
/*
$('.E4, .E5').addClass('E'); // After this statement, we have a hook
$('.E').appendTo($('.C45')); // Objective is accomplished
This is is an extra step that should be taken during load time if you cannot hardcode anything in the HTML or CSS. A quick comparison:
OP Code
<div class='element1'>Element</div>
<div class='element2'>Element</div>
<div class='element3'>Element</div>
<div class='element4'>Element</div>
<div class='element5'>Element</div>
<div class='element6'>Element</div>
<div class='element7'>Element</div>
<div class='element8'>Element</div>
<div class='element9'>Element</div>
Each element has a unique identifier: .element${1,2,3,...6}
.
Must totally rely on some data to determine which element(s) to grab...
New Code
<div class='element1 element nested'>Element</div>
<div class='element2 element nested'>Element</div>
<div class='element3 element solo'>Element</div>
<div class='element4 element solo'>Element</div>
<div class='element5 element test'>Element</div>
<div class='element6 element data' data-stat='3'>Element</div>
<div class='element7 element'>Element</div>
<div class='element8 element solo'>Element</div>
<div class='element9 element solo'>Element</div>
- Each element has a unique identifier:
.element${1,2,3,...6}
.
- Each element belongs to a common group:
.element
.
- Each element belongs to a sub group:
.element1
and .element2
are .nested
.
Collect all .nested
elements and add them to .container
:
$('.container').append($('.nested'));
If .test
passes (true), then get .data
, and change as many .solo
elements into .nested
indicated by data-stat
value of .data
.
if(test) {
let stat = $('.data').data('stat');
var array = $('.solo').toArray();
for (let i = 0; i < parseFloat(stat); i++) {
let node = array[i];
$(node).removeClass('solo').addClass('nested');
}
}
Try that with the OP code, JK.
Last 4 Examples: C67, C89, CAB, & CCD
The last 4 Examples accomplish the same goal as before, but the
point of the Demo is to show different ways that 2 divs can be
placed in another div. Each of these Examples parse a string into HTML.
C67: jQuery html()
method:
Use Template Literals instead of String Literals to create a htmlString:
`<div class="E6"></div><div class="E7"></div>`;
String will be parsed into HTML inside $('C67')
; anything inside of $('.67')
beforehand is overwritten.
$('.C67').html(`<div class="E6"></div><div class="E7"></div>`);
C89: jQuery replaceWith()
method:
It replaces $(selector)
with a given parameter which can be a jQuery Object, a DOM Object, Array, htmlString, etc...
In the Example, .C89
is replaced by a htmlString duplicate of itself with .E8
and .E9
already nested within it.
$(".C89").replaceWith({`<div class="C89">
<div class="E8"></div>
<div class="E9"></div>
</div>`});
CAB: Plain JavaScript property innerHTML
:
html()
is innerHTML
with some checks. Note: the jQuery get(0)
method included in the statement below:
$('.CAB').
get(0).innerHTML="<div class='EA'></div><div class='EB'></div>"
;
- When using Plain JavaScript methods and properties on a jQuery Object, we must Dereference the jQuery Object which in turn changes it into a DOM Object. More importantly, we have taken advantage of using a jQuery Object to reference an element and use JavaScript methods/properties which on the average more verbose than jQuery but it is faster (speed is not noticeable on small scale of course).
CCD: Plain JavaScript method insertAdjacentHTML()
:
- This method blows the doors off of any HTML parser from JavaScript and jQuery. It's flexible, fast and actually safer than any other HTML parser because unlike the others like
innerHTML
and .html()
, iAHTML()
inserts the String into or around the target element, it never overwrites and destroys content.
Note: the bracket notation included in the statement below.
$('.CCD')[0].insertAdjacentHTML('beforeend', '<div class="EC"></div>
<div class="ED"></div>');
The [0]
is another way to dereference a jQuery Object (see Example CAB).
Demo
Testing
- Click any blue (cyan) text.
- A window should slide open revealing code in green text.
- Click the button on the left bottom corner.
//C01~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/* EXAMPLE C01 */
function C01(e) {
$('.E0, .E1').prependTo($('.C01'));
}
//C23~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/* EXAMPLE C23 */
function C23(e) {
$('.C23').wrapInner($('.E2, .E3'));
}
//C45~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/* EXAMPLE C45 */
function C45(e) {
$('.E4, .E5').addClass('E');
$('.E').appendTo($('.C45'));
}
//C67~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/* EXAMPLE C67 */
function C67(e) {
var E67 = `<div class='E6'></div>
<div class='E7'></div>`;
$('.C67').html(E67);
}
//C89~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/* EXAMPLE C89 */
function C89(e) {
var CE89 = `<div class='C89'>
<div class='E8'></div>
<div class='E9'></div>
</div>`;
$('.C89').replaceWith(CE89);
}
//CAB~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/* EXAMPLE CAB */
function CAB(e) {
var CEAB = `<div class='EA'></div>
<div class='EB'></div>`;
$('.CAB').get(0).innerHTML = CEAB;
}
//CCD~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/* EXAMPLE CCD */
function CCD(e) {
var CECD = `<div class='EC'></div>
<div class='ED'></div>`;
var CCD = $('.CCD')[0];
CCD.insertAdjacentHTML('beforeend', CECD);
}
html,
body {
font: 900 16px/1 Consolas;
}
main {
display: flex;
flex-flow: row nowrap;
}
dl {
margin: 0 0 0 5px
}
details {
background: #000;
}
summary {
font:400 18px/1.2 "Palatino Linotype";
color:cyan;
cursor: pointer;
}
section {
display: flex;
flex-flow: column nowrap;
width: 30%;
}
section:first-of-type {
width: 65%
}
[class^=C] {
border: 2.5px 5px 2.5px 5px;
border-style: ridge;
border-color: tomato;
height: 60px;
padding: 5px 5px 10px;
background: rgba(51, 51, 51, 0.1);
}
/* This declaration enables each matched node to display its
classList as text content */
[class^=C]::before,
[class^=E]::before {
content: attr(class);
}
[class^=E] {
border: 4px 3px 4px 3px;
border-style: inset;
border-color: navy;
text-align: center;
background: rgba(11, 11, 11, 0.6);
color: yellow;
}
.jQIndex {
width: 35%;
display: inline-block;
align-self: flex-start;
line-height: 50px;
}
pre {
margin: 0;
padding: 5px;
}
code {
white-space: pre-wrap;
padding: 0;
margin: 0;
background: #000;
color: lime;
}
dt {
margin-left: 10px
}
<main>
<section>
<!--BEGIN EXAMPLE C01-->
<div class='C01'></div>
<div class='E0'></div>
<div class='E1'></div>
<details>
<summary>C01 prependTo()</summary>
<pre><code>
$('.E0, .E1').prependTo($('.C01'));
</code></pre>
<button onclick='C01()'>prependTo</button>
</details>
<!--=END EXAMPLE C01=-->
<!--BEGIN EXAMPLE C23-->
<div class='C23'></div>
<div class='E2'></div>
<div class='E3'></div>
<details>
<summary>C23 wrapInner()</summary>
<pre><code>
$('.C23').wrapInner($('.E2, .E3'));
</code></pre>
<button onclick='C23()'>wrapInner</button>
</details>
<!--=END EXAMPLE C23=-->
<!--BEGIN EXAMPLE C45-->
<div class='C45'></div>
<div class='E4'></div>
<div class='E5'></div>
<details>
<summary>C45 addClass()/appendTo()</summary>
<pre><code>
$('.E4, .E5').addClass('E');
$('.E').appendTo($('.C45'));
</code></pre>
<button onclick='C45()'>addClass/apendTo</button>
</details>
<!--=END EXAMPLE C45=-->
<!--BEGIN EXAMPLE C67-->
<div class='C67'></div>
<details>
<summary>C67 html()</summary>
<pre><code>
var E67 =` <div class='E6'></div>
<div class='E7'></div>`;
$('.C67').html(E67);
</code></pre>
<button onclick='C67()'>html</button>
</details>
<!--=END EXAMPLE C67=-->
<!--BEGIN EXAMPLE C89-->
<div class='C89'></div>
<details>
<summary>C89 replaceWith()</summary>
<pre><code>
var CE89 = `<div class='C89'>
<div class='E8'></div>
<div class='E9'></div>
</div>`;
$('.C89').replaceWith(CE89);
</code></pre>
<button onclick='C89()'>replaceWith</button>
</details>
<!--=END EXAMPLE C89=-->
<!--BEGIN EXAMPLE CAB-->
<div class='CAB'></div>
<details>
<summary>CAB innerHTML</summary>
<pre><code>
var CEAB =`<div class='EA'></div>
<div class='EB'></div>`;
$('.CAB').get(0).innerHTML = CEAB;
</code></pre>
<button onclick='CAB()'>innerHTML</button>
</details>
<!--=END EXAMPLE CAB=-->
<!--BEGIN EXAMPLE CCD-->
<div class='CCD'></div>
<details>
<summary>CCD insertAdjacentHTML()</summary>
<pre><code>
var CECD = `<div class='EC'></div>
<div class='ED'></div>`;
var CCD = $('.CCD')[0];
CCD.insertAdjacentHTML('beforeend', CECD);
</code></pre>
<button onclick='CCD()'>insertAdjacentHTML</button>
</details>
<!--=END EXAMPLE CCD=-->
</section>
<!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-->
<section>
<nav class='jQIndex'>
<dl>
<dt>jQuery</dt>
<dd>
<a href='https://api.jquery.com/prependTo/'>prependTo()</a>
</dd>
<dd> </dd>
<dd>
<a href='https://api.jquery.com/wrapInner/'>wrapInner()</a>
</dd>
<dd>
<a href='https://api.jquery.com/addClass/'>addClass()</a>
</dd>
<dd>
<a href='https://api.jquery.com/appendTo/'>appendTo()</a>
</dd>
<dd> </dd>
<dd>
<a href='https://api.jquery.com/html/'>html()</a>
</dd>
<dd> </dd>
<dd>
<a href='https://api.jquery.com/replaceWith/'>replaceWith()</a>
</dd>
<dt>JavaScript</dt>
<dd>
<a href='https://stackoverflow.com/a/43665202/2813224'>insertAdjacentHTML() vs. innerHTML</a>
</dd>
<dt>Miscellaneous</dt>
<dd>
<a href='https://api.jquery.com/category/selectors/'>Selectors</a>
</dd>
<dd>
<a href='https://oscarotero.com/jquery/#selectors'>jReference</a>
</dd>
<dd>
<a href='https://learn.jquery.com/using-jquery-core/faq/how-do-i-pull-a-native-dom-element-from-a-jquery-object/'>Dereferencing</a></dd>
</dl>
</nav>
</section>
</main>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>