简体   繁体   中英

Change the type of element using jQuery

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>';
});

Working example

You can do this:

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

http://jsfiddle.net/teBuN/

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(....) .............

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM