Reputation: 11012
I need to replace <p> </p>
with <p class="spacer"> </p>
I tried this option using replaceAll but it doesn't work.
$('<p class="spacer"> </p>').replaceAll( "<p> </p>" );
What is the correct way to do this?
Upvotes: 0
Views: 46
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
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> </p>" );
$( ".spacer" ).replaceWith( "<p>test test</p>" );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<p class="spacer"> </p>
</div>
enter code here
Upvotes: 1
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 === " "
}).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> </p>
<p>A</p>
<p> </p>
<p>A</p>
<p> </p>
<p>A</p>
<p> </p>
<p> </p>
<p> </p>
<p>A</p>
Upvotes: 2