简体   繁体   English

如何使用 Jquery 将 HTML 元素移到其容器之外?

[英]How can i move HTML elements outside their containers using Jquery?

I need to move the p tag in each container outside it's container, so i need to move "some text 1" outside its container and the same to the next paragraph , but what i'm getting is the both of them are moving out side the containers我需要将每个容器中的 p 标签移到它的容器之外,所以我需要将“一些文本 1”移到它的容器之外,并且与下一段相同,但我得到的是它们都移到了外面容器

 $(document).ready(function() { $('.select-p-container p').each(function () { $(this).insertBefore('.select-p-container'); }) });
 .select-p-container{ border:1px solid red; max-width:450px; margin-bottom: 20px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container"> <div class="select-container"> <div class="select-p-container"> <p>Some text 1</p> <select name="" id=""> <option value="1">1</option> <option value="1">2</option> <option value="1">3</option> </select> </div> <div class="select-p-container"> <p>Some text 2</p> <select name="" id=""> <option value="1">1</option> <option value="1">2</option> <option value="1">3</option> </select> </div> </div> </div>

You need to properly limit the scope of your element selection.您需要适当地限制元素选择的范围。

$(this).insertBefore('.select-p-container')

.select-p-container selects all elements with that class, across the whole document. .select-p-container在整个文档中选择该类的所有元素。

You need only the element, that is the actual parent of the current paragraph:您只需要元素,即当前段落的实际父元素:

$(this).insertBefore($(this).parent());

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

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