changing <span> to <p> through DOM
I am receiving a piece of HTML code from a plugin and I want to change all instances of <span class="post-stats">
to <p class="post-stats">
in the code. What is the best way开发者_开发技巧 to achieve this?
Maybe replaceWith()
would work?
$('span.post-status').replaceWith(function()
{
return '<p class="post-stats">' + $(this).html() + '</p>';
});
Instead of doing all this stuff, why not just make the <span>
act like a <p>
with CSS? Adding this to your stylesheet should suffice.
span.post-status
{
display: block;
}
Or, if you insist on jQuery:
$('span.post-status').css('display', 'block');
$('.post-stats').each(function(i,elem){
$(elem).replaceWith('<p class="post-stats">'+$(elem).html()+'</p>');
});
Here's an example
Perhaps you're looking for .replaceWith
?
$('span.post-stats').replaceWith(function(){
return $('<p>').addClass('post-stats').html($(this).contents());
});
Demo
I know I'm a little late, but not a fan of using the .each
or .html(.html())
method(s). I also think you should use .text()
or .addClass
whenever possible keeping HTML markup where it belongs, and leave javascript to manipulating the propert(y/ies).
var spanPostStats = $( 'span.post-stats' );
spanPostStats.replaceWith(
$( '<p>' ).addClass( 'post-stats' ).html( spanPostStats.html() )
);
http://jsfiddle.net/JAAulde/nEJG2/
I would use jQuery, look at the following function: http://api.jquery.com/replaceWith/
精彩评论