简体   繁体   中英

How to move a node element to be the first inside its parent element

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id='parent'> <div>B</div> <div>C</div> <div onload='this.parentNode.prependChild();'>A</div> </div> 

I tried to move the <div>A</div> to the top of all child elements with inline script but didn't work with prependChild() , What is my mistake?

You can only attach the onload event handler to the body element. However, it is fairly simple to move the last child to be the first within its parent:

 $('#parent').prepend($('#parent > div:last-child')) 
 down vote favorite <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id='parent'> <div>B</div> <div>C</div> <div>A</div> </div> 

You can add javascript in the head section and have a window.onload over there. The following will place the element first in your parent div. This is vanilla javascript. Which will work even with jQuery... Your choice!

 window.onload = function() { var parent = document.getElementById("parent"); var elem = document.getElementById("thisone"); parent.prepend(elem); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id='parent'> <div>B</div> <div>C</div> <div id="thisone">A</div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM