Getting some weird behavior with a piece of code that's supposed to do simple DOM manipulation:
b.detach();
b.insertAfter(a);
a.remove();
Initially the HTML looks like
<a>
<b> </b>
</a>
(if it matters, I'm using b.wrap('<a></a>')
to build it)
After that code runs it's supposed to move b
after a
:
<a></a>
<b></b>
then remove a
:
<b></b>
but it doesn't. Instead a
remains there and b
just disappears. Any ideas on what could be wrong?
I tried using after()
instead, reversing arguments, but getting the same result.
remove b.detach() b.insertAfter(a); will move it
I'm not sure what you mean, if I try it, it works the way you want it:
HTML:
<div id="test">
<a>
Test <b>Test</b>
</a>
</div>
<button id="change_dom">manipulate</button>
<br />
<textarea id="result"></textarea>
JS:
$(document).ready(function(){
$('#change_dom').click(function(){
var a = $('a'),
b = $('b');
b.detach();
b.insertAfter(a);
a.remove();
$('#result').val($('#test').html());
});
});
Update:
This is how it can be done in the scenario described in this fiddle: http://jsfiddle.net/8wy7v/1/
var list = b.parents('ul')
b.insertAfter(list);
list.remove();
The reason is that wrap
does clone the elements - so what is referenced by a
never actually contains b
. Btw, the detach
is superfluous, as elements will be automatically removed when inserted elsewhere in the DOM.
So to get the a
after which to insert, you will need to reselect it (eg by b.parent()
).
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.