TheWandererr TheWandererr - 3 months ago 8
HTML Question

AppendChild a element above a cerain element

So i have a div element which will be filled dynamically with others divs using the appendChild Method, this should display a list. The User is now able to sort that list with the JqueryUI Sortable option.
I also added some sortable option attribues like follows:


Options:

$("#NameContainer").sortable("option", "axis", "y");
$("#NameContainer").sortable( "option", "containment", "parent" );



LIST

<div id="NameContainer" class="ui-widget">
<div id="Name_1">John</div>
<div id="Name_2">Jack</div>
<div id="Name_3">Charlie</div>
<div id="Name_4">Sawyer</div>
<div id="Name_5">Yin</div>
<div id="Name_6">Ben</div>
</div>



Now comes my problem. The appendChild always inserts the new div at the bottom of the container but i want to to add some space at the bottom of to the Container Div with a "br" or something like that. I want to add that space to make sure that when the user sorts the last item of that list it will get sorted correctly because the "containment" bounds sometimes wont allow to sort under the last item.


<div id="NameContainer" class="ui-widget">
<div id="Name_1">John</div>
<div id="Name_2">Jack</div>
<div id="Name_3">Charlie</div>
<div id="Name_4">Sawyer</div>
<div id="Name_5">Yin</div>
<div id="Name_6">Ben</div>
<br><!--SPACEHOLDER-->
</div>



So here comes my Question is there away to appendChild above a certain element?
Like a "br" "div" or "p"?

Ish Ish
Answer

Try this instead of appendChild:

Please note I have used random value to add in div as I don't have your dynamic value.

check fiddle: https://jsfiddle.net/dqx9nbcy/

  <div id="NameContainer" class="ui-widget">
     <div id="divspacer"></div> 
   </div>
   <button id="btn">ADD Element</button>

  $(document).ready(function(){
    $("#btn").click(function(){
       var parentnode = document.getElementById("NameContainer");
       var existnode = document.getElementById("divspacer");
       var rand = Math.floor((Math.random() * 10) + 1);
       var newName = document.createElement("div");   
       newName.setAttribute("id", rand); 
       newName.setAttribute("value", rand);
       newName.setAttribute("class","ui-widget-content");
       newName.innerHTML = rand; 
       parentnode.insertBefore(newName,existnode);
    });
});