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.
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.
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>';
});
You can do this:
var a = $('#p').text();
$('#p').replaceWith('<span id="#p">' + a + '</span>');
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?
$("p").replaceWith(....) .............