简体   繁体   English

如何将节点元素移动为其父元素中的第一个元素

[英]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? 我尝试使用内联脚本将<div>A</div>移至所有子元素的顶部,但不适用于prependChild() ,这是什么错误?

You can only attach the onload event handler to the body element. 您只能将onload事件处理程序附加到body元素。 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. 您可以在头部添加javascript,并在其上方添加window.onload。 The following will place the element first in your parent div. 下面将把元素放在您的父div中的第一位。 This is vanilla javascript. 这是香草javascript。 Which will work even with jQuery... Your choice! 即使使用jQuery也可以使用...您的选择!

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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