最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - change the order of elements to the top - Stack Overflow

programmeradmin2浏览0评论
   <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?.

Share Improve this question edited May 23, 2017 at 10:28 CommunityBot 11 silver badge asked May 12, 2012 at 11:25 Sami Al-SubhiSami Al-Subhi 4,67210 gold badges47 silver badges75 bronze badges 2
  • 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
Add a ment  | 

4 Answers 4

Reset to default 9
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

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

发布评论

评论列表(0)

  1. 暂无评论