-1

I have this HTML structure:

<div>something</div>
<p>this is a paragraph</p>

Now I want to replace that <p> with <span>. Something like this;

<div>something</div>
<span>this is a span</span>

I want something like this:

$("div").siblings("p"). /* replace with "<span>this is a span</span>" */

Note: There isn't any wrapper around that <p>. So I cannot use .html().


Well, doing that is possible?

stack
  • 10,280
  • 19
  • 65
  • 117

3 Answers3

1

Considering given html, you can do it this way:

$("div").next("p").replaceWith('<span>This is a span</span>'); 
The Process
  • 5,913
  • 3
  • 30
  • 41
1

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

<div class="container">
  <div class="inner first">Hello</div>
  <div class="inner second">And</div>
  <div class="inner third">Goodbye</div>
</div>

The second inner <div> could be replaced with the specified HTML:

$( "div.second" ).replaceWith( "<h2>New heading</h2>" );

This results in the structure:

<div class="container">
  <div class="inner first">Hello</div>
  <h2>New heading</h2>
  <div class="inner third">Goodbye</div>
</div>

See http://api.jquery.com/replacewith/

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Tim Spencer
  • 131
  • 7
1

You can use this:

$('p').replaceWith(function(){
    return $("<span />", {html: $(this).html()});
});

See fiddle: http://jsfiddle.net/DIRTY_SMITH/k2swf/592/

Adam Buchanan Smith
  • 9,422
  • 5
  • 19
  • 39