jQuery:如何仅拆分指定元素而不删除其父容器?
How to Restructure DOM Elements with jQuery (Fixing the
unwrap() Issue) Got it, let's break down how to get your desired DOM structure without accidentally wiping out the entire parent div. The problem with unwrap() here is that it removes the direct parent element of your target (#x2), which deletes the whole wrapping div and leaves all three spans as siblings—totally not what you want.
Here's a straightforward, step-by-step solution that delivers exactly the structure you're after:
Working jQuery Code
// 1. Grab the original parent div that wraps all three spans const originalParent = $('#x1').parent(); // 2. Move #x2 out of the original div and place it right after the div $('#x2').insertAfter(originalParent); // 3. Take #x3 out of the original div, wrap it in a new div, then place it after #x2 originalParent.find('#x3').detach().wrap('<div></div>').insertAfter('#x2');
Let's Walk Through the Process
- Initial DOM Structure:
<div> <span id="x1"></span> <span id="x2"></span> <span id="x3"></span> </div> - After moving
#x2withinsertAfter():<div> <span id="x1"></span> <span id="x3"></span> </div> <span id="x2"></span> - After detaching, wrapping, and moving
#x3:<div> <span id="x1"></span> </div> <span id="x2"></span> <div> <span id="x3"></span> </div>
Why This Works
insertAfter()moves the target element to a new position in the DOM without removing any parent elements (unlikeunwrap()which deletes the parent entirely).detach()safely removes#x3from the original div while preserving its jQuery data and events (a safer alternative toremove()here).wrap()adds the new div wrapper around#x3exactly where you need it, completing your desired structure.
内容的提问来源于stack exchange,提问作者Kacper G.
相关产品推荐
相关产品推荐

