1

I'm using Jquery 3.4.1. I'm trying to replace the img tag in my html with dynamically created div element. But it is always getting rendered as plain text instead of html.

HTML:

<p class="post-content">
    <img src="..." />
</p>

Script:

$.each($('.post-content img'), function () {
    const imgSrc = this.src;
    this.closest('p').replaceWith(`<div class="post-image"><div class="post-image-cover" style="background-image: url(${imgSrc})"></div></div>`)
});

Current Output:

enter image description here

Expected Output:

Above text html needs to be rendered as HTML element.

Please assist on where I'm wrong?

4
  • Have you tried using .html() and not .replaceWith(), this will maybe solve the problem you are facing. Looks like if you do $(this).closest('p').html() it works Commented Mar 22, 2020 at 2:49
  • But I need to replace the p tag with my html. I don't want to place the element inside p tag. Commented Mar 22, 2020 at 2:55
  • Try with $(this).closest('p')[0].outerHTML = '<div class Commented Mar 22, 2020 at 3:09
  • hmm that works. Can you please explain how this works? Commented Mar 22, 2020 at 3:27

1 Answer 1

3

You need to use $(this). instead of this. - to invoke jQuery functionality and not native JS, which works differently.

$.each($('.post-content img'), function() {
  const imgSrc = this.src;
  $(this).closest('p').replaceWith(`<div class="post-image"><div class="post-image-cover" style="background-image: url(${imgSrc})">Test replacement</div></div>`)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="post-content">
  <img src="..." />
</p>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.