I currently have an "Add more" button that when clicked, duplicates a div I have. The problem currently is when the button is clicked and the div duplicates, it appears below the "Add more" button. I want the div to duplicate right under the original div when clicked, this also means the duplicate will be above the "Add more" button. How do I go about doing this?
HTML
<!-- Instrument Exp. -->
<div>
<label>What instruments and level do you want to teach?</label>
<div class="form-inline justify-content-center" id="ins_1">
<!-- Instrument 1 -->
<div>
<select class="form-control ins">
<option>Instrument</option>
<option>Cello</option>
<option>Clarinet</option>
<option>Drums</option>
<option>Flute</option>
<option>Guitar</option>
<option>Piano</option>
<option>Saxophone</option>
<option>Violin</option>
<option>Vocal</option>
<option>Trumpet</option>
</select>
</div>
<!-- Level 1 -->
<div>
<select class="form-control lvl">
<option>Level</option>
<option>Beginner</option>
<option>Advanced</option>
<option>Intermediate</option>
</select>
</div>
</div>
<!-- Add More -->
<div class="text-center" id="add_more">
<button type="button" class="no_link" onclick="add_instrument()">Add more +</button>
</div>
</div>
JavaScript
var i = 0;
var original = document.getElementById('ins_1');
function add_instrument() {
var clone = original.cloneNode(true);
clone.id = "ins_1" + ++i;
original.parentNode.appendChild(clone);
}
See insertBefore, https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore. If you combine it with nextSibling, you can have it add right after it:
Also see: How to insert an element after another element in JavaScript without using a library?
Edit: As @Tej pointed out in the comments, there are nice functions to insert nodes adjacently: insertAdjacentHTML, and insertAdjacentElement.
insertAdjacentElement
requires IE8+ or a recent browser.The code becomes more readable with those functions, in my opinion:
appendChild
inserts the node as the last child of the node. In this case, that's after the 'add more' button because your list and button are children within the same element.Solution 1
Put your list of new instruments in a different element so appending to the end of the parent has the desired effect.
Solution 2
Use insert before and insert before the "add more button".
Solution 3 (not recommended)
Append the "add more" button appending the new instrument item to place it back at the end of the list.