开发者

jQuery replaceWith not working while replacing with three elements

开发者 https://www.devze.com 2023-02-09 20:00 出处:网络
I\'m trying to replace a single element with three other elements, using jQuery\'s replaceWith, but it doesn\'t seem to be working.

I'm trying to replace a single element with three other elements, using jQuery's replaceWith, but it doesn't seem to be working.

HTML:

<span>first</span>
<span>second</span>
<span>third</span>

JS:

var spans = $("span");
spans.eq(1).replaceWith("<span></span><span></span><span></span>");

This should if I'm write, result in:

<span>first</span>
<span></span><span></span><span></span>
<span>third</span>

But nothing changes...any thoughts?

EDIT: This was meant as an example, I didn't take into account a difference between actual dom and generated dom (is there a difference? It ap开发者_开发技巧pears so...)

var spans = $("<span>first</span><span>second</span><span>third</span>");
spans.eq(1).replaceWith($("<span></span><span></span><span></span>"));

So there's a more accurate portrayal of my code.


Edit. Check http://jsfiddle.net/z9VDw/3/ . Seems you have to append disconnected DOM nodes before doing such manipulation.


Now that I see what you're trying to do it won't work. Dom manipulation with fragments doesn't work in jQuery. (Other than setting attributes/css.) replaceWith inserts the value before the next elements. In this case <span>third</span> and then returns this again, which is whatever this was before you called replaceWith. Which was <span>second</span>

0

精彩评论

暂无评论...
验证码 换一张
取 消