Question

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 appears 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.

Was it helpful?

Solution

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

OTHER TIPS

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>

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top