5
   <div id="container">
        <div id="1">1</div>
        <div id="2">2</div>
        <div id="3">3</div>
        <div id="4">4</div>
   </div>         

how to move the div #4 to the top using pure javascript I saw this but it's working only to move elements to the bottom. for example that will work to move #1 to the bottom. it will work to move #4 to the top by moving all the other elements to the bottom. isn't there a direct way to move #4 to the top?.

Community
  • 1
  • 1
Sami Al-Subhi
  • 4,406
  • 9
  • 39
  • 66

4 Answers4

8
var _4th = document.getElementById('4'); // BTW. numeric IDs are not valid
var parent = _4th.parentNode;
var _1st = parent.firstChild;

parent.insertBefore(_4th, _1st);

a JSFiddle example

Rafael
  • 18,349
  • 5
  • 58
  • 67
0

You can try this:

var container = document.getElementById("container");
var el = document.getElementById("4")​;
container.insertBefore(el, container.firstChild);
VisioN
  • 143,310
  • 32
  • 282
  • 281
-1

jQuery solution is,

Your HTML is,

    <div id="container">
        <div id="1">1</div>
        <div id="2">2</div>
        <div id="3">3</div>
        <div id="4">4</div>
   </div>  ​

Some additional css,

#container {
    border:1px solid #888;
    padding:10px;
    margin:5px;
    border-radius:10px;
}
#container div{
    border:1px solid #Cda12a;
    margin:5px;
    text-align:center;
    height:25px;
    color:#fff;
    background:#000;
}

​ And the JavaScript code is,

$(function() {
    $( "#container" ).sortable();
    $( "#container" ).disableSelection();
});​

Please refer working example here

Umesh Aawte
  • 4,590
  • 7
  • 41
  • 51
-2
jQuery("#4").before(jQuery("#1").html());

try this

Rizstien
  • 802
  • 1
  • 8
  • 23