4

If I know the ID of an element, is it possible to change the type of HTML tag that it has?

For example if you have <p id="p">Lots and lots of text here.</p>, is it possible to change it to <span id="p">....?

Thanks.

David Gard
  • 11,225
  • 36
  • 115
  • 227

4 Answers4

9

You can use the replaceWith method to do this. You'll need to rebuild the attributes for the replacement though.

$('#p').replaceWith(function(){
   return '<span>' + $(this).contents().text() + '</span>';
});

Working example

Jamie Dixon
  • 53,019
  • 19
  • 125
  • 162
2

You can do this:

var a = $('#p').text();
$('#p').replaceWith('<span id="#p">' + a + '</span>');

http://jsfiddle.net/teBuN/

Jason Gennaro
  • 34,535
  • 8
  • 65
  • 86
2
var el = document.getElementById(id);
var new = document.createElement("span");
new.id = el.id;
[].forEach.call(el.childNodes, function (node) {
  new.appendChild(node);
});
el.parentNode.replaceChild(new, el);

Now, a good question, is why. Why would you want to change the html element?

Surely you choose the most semantic element for this piece of data, why would another element be a better choice?

Raynos
  • 166,823
  • 56
  • 351
  • 396
1
$("p").replaceWith(....) .............
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • 1
    I think David is looking for $("#p").replaceWith(...) to replace one particular element in the DOM with the id of "p", versus replacing all paragraph tags with the same new content. – Todd Nov 07 '11 at 14:43
  • @RoyiNamir - This did get me on the right path though, as I did not know of the existence of `replaceWith()`. Thanks. – David Gard Nov 07 '11 at 14:51
  • so select the answer who helped you. – Royi Namir Nov 07 '11 at 14:57