Change item type with jQuery

If I know the identifier 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> , can you change it to <span id="p">.... ?

Thanks.

+4
source share
4 answers

You can use the replaceWith method for this. You will need to rebuild the attributes to replace.

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

Working example

+9
source

You can do it:

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

http://jsfiddle.net/teBuN/

+2
source
 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, the good question is why. Why do you want to change the html element?

Of course, you choose the most semantic element for this piece of data, why should another element be a better choice?

+2
source
 $("p").replaceWith(....) ............. 
+1
source

Source: https://habr.com/ru/post/1380010/


All Articles