Question

I want to replace certain divs with other divs. But I want to do it all at a time.

divs_to_replace.eq(-1).after(new_divs).end().remove();

So I thought I should use replaceWith() instead as it does that at once:

divs_to_replace.replaceWith(new_divs);

However this replaces the old divs with the new ones one by one. So I have as many old divs there are times duplicated new divs. Is there a way I can do this all at once?

EDIT:

http://jsfiddle.net/9ej2n/ (Working solution)

http://jsfiddle.net/9ej2n/1/ (Desired solution)

EDIT2: (..content..)

<div class="article">
    (..content..)
</div>

<div class="article">
    (..content..)
</div>

<div class="article">
    (..content..)
</div>

<div class="empty_article"></div>
<div class="empty_article"></div>
<div class="empty_article"></div>
<div class="empty_article"></div>

Now I load new articles with content via AJAX into the page and replace the empty_articles with this new ones.

I tried to make the example simple to go to the point. Anyway this is more real example. I thought it would be better for performance to use replaceWith() instead of the before approach.

Était-ce utile?

La solution

If you are insisting on using replaceWith, then you may wrap them first:

divs_to_replace.wrapAll("<div/>").parent().replaceWith(new_divs);

Fiddle: http://jsfiddle.net/9ej2n/3/

Wrap them and then replace the parent.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top