<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?.
<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?.
- Better use jQuery or other suitable javaScript framework – Umesh Aawte Commented May 12, 2012 at 11:29
- 2 my website is nearly done. I don't want to add a framework just for this feature. – Sami Al-Subhi Commented May 12, 2012 at 11:32
4 Answers
Reset to default 9var _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
You can try this:
var container = document.getElementById("container");
var el = document.getElementById("4");
container.insertBefore(el, container.firstChild);
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
jQuery("#4").before(jQuery("#1").html());
try this