ivanibash
ivanibash

Reputation: 1491

How to use replaceWith to replace the content to in dom

I have the following code:

myHtml = '
  <div class="outer">
    <div class="inner"></div>
    <div class="inner"></div>
    <div class="inner"></div>
    <div class="inner"></div>
  </div>'

$(myHtml).find('.inner').replaceWith('<h2>hello</h2>')

console.log(myHtml)

I am trying to replace my inner divs with some other content, but myHtml doesn't change after running replaceWith. I suspect it is because it's not part of the DOM tree. Am I right? How do I work around this?

Thanks

Upvotes: 0

Views: 539

Answers (1)

Taplar
Taplar

Reputation: 24965

//fix the new lines in the string
myHtml = '\
  <div class="outer">\
    <div class="inner"></div>\
    <div class="inner"></div>\
    <div class="inner"></div>\
    <div class="inner"></div>\
  </div>';

//store the changed html back in the string
myHtml = $(myHtml)
           .find('.inner')
           .replaceWith('<h2>hello</h2>')
           //end the find() to go back to the orignal Elements
           .end()
           //get the new complete html
           .prop('outerHTML');

console.log(myHtml)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 1

Related Questions