Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change the order of elements to the top

Tags:

javascript

   <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?.

like image 524
Sami Al-Subhi Avatar asked May 12 '12 11:05

Sami Al-Subhi


1 Answers

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

like image 68
Rafael Avatar answered Sep 30 '22 05:09

Rafael