Jquery replaceWith deletes element when exchanging in several places

Asked

Viewed 31 times

0

I’m having a problem with the function call replaceWith of Jquery.

I have a variable that is storing an HTML structure, this structure I want to render in several different places (this works when I have several blocks replaced at once), when I make the change using the replaceWith for the second time, it erases the place where I made the exchange for the first time, and so on.

How do I replace the content elsewhere, without deleting where it already has?

Note: I can not make the exchange in several places at once, I have to do in element by element.

Example:

<div class="bloco1"></div>
<div class="bloco2"></div>

<div id="conteudo">Isso deve ir para todas as DIVs</div>

<script>
    $('.bloco1').replaceWith($('#conteudo'));
    $('.bloco2').replaceWith($('#conteudo'));
</script>

When executing the block of script, there’s only one div with the text.

1 answer

3


Clone the element.

If you pass an element as a parameter to the method replaceWith, the method will move the element to the new DOM location.

If the idea was to create a new element equal to the past as parameter, and keep the original in its place, then create a new element using the original as base and pass it as parameter to the method:

$('.bloco1').replaceWith($('#conteudo').clone());
$('.bloco2').replaceWith($('#conteudo').clone());
  • This solves one problem but generated another, the blocks are not copying the events applied to the objects.

  • Actually, event listeners are not part of the element. If you need the clones of the elements to have the same listeners, you will have to apply the listeners to them as well, or use Event-delegation. If in doubt, ask a new question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.