Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change tag using javascript [duplicate]

I want to know how can I change a tag with pure javascript like that

    <span>some text</span> 

I want to change it to that

  <div>some text</div> 

I have no idea how to do it.

like image 937
user1801625 Avatar asked Nov 15 '12 00:11

user1801625


People also ask

How to change tag using JavaScript?

getElementById('foo'). innerHTML; original_html = original_html. replace("<span>", "<div>"); original_html = original_html. replace(new RegExp("</span>"+$), "</div">) document.

How to change a element in html using JS?

To change HTML element type with JavaScript, we can use the replaceWith method. For instance, we write: const parent = document. createElement("div"); const child = document.

How do I change the name of my element tag?

You can't change the tag name of an existing DOM element; instead, you have to create a replacement and then insert it where the element was.


1 Answers

You can't change the type of an element like that, instead you have to create a new element and move the contents into it. Example:

var e = document.getElementsByTagName('span')[0];  var d = document.createElement('div'); d.innerHTML = e.innerHTML;  e.parentNode.replaceChild(d, e); 

Demo: http://jsfiddle.net/Guffa/bhnWR/

like image 129
Guffa Avatar answered Oct 11 '22 12:10

Guffa