forrest
forrest

Reputation: 11012

How do I replace an HTML String with another one?

I need to replace <p>&nbsp;</p> with <p class="spacer">&nbsp;</p>

I tried this option using replaceAll but it doesn't work.

$('<p class="spacer">&nbsp;</p>').replaceAll( "<p>&nbsp;</p>" );

What is the correct way to do this?

Upvotes: 0

Views: 46

Answers (3)

Bruce Chamoff
Bruce Chamoff

Reputation: 41

It does not look like you are trying to replace HTML more than just add a class attribute. If so, this also works as I tested it in my browser. You would have jQuery add the class attribute like this:

        $(document).ready(function(){
            $('p').attr('class','spacer');
        });

However this would target ALL P tags, so if this is the first one, you can use

        $(document).first().ready(function(){
            $('p').attr('class','spacer');
        });

Bruce

Upvotes: 0

yathavan
yathavan

Reputation: 2376

try .replaceWith() The .replaceWith() method removes content from the DOM and inserts new content in its place with a single call. Consider this DOM structure:

$( ".spacer" ).replaceWith( "<p>&nbsp;</p>" );

$( ".spacer" ).replaceWith( "<p>test&nbsp;test</p>" );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <p class="spacer">&nbsp;</p>
</div>

enter code here

Upvotes: 1

epascarello
epascarello

Reputation: 207547

All you are doing is adding a class so loop over and find the elements that match and add the class.

$("p").filter(function() {
  return this.innerHTML === "&nbsp;"
}).addClass("spacer");
.spacer {
  background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>A</p>
<p>&nbsp;</p>
<p>A</p>
<p>&nbsp;</p>
<p>A</p>
<p>&nbsp;</p>
<p>A</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>A</p>

Upvotes: 2

Related Questions