Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change HTML tag type

Tags:

Can I replace one HTML element with another?

But I don't want to make the content blank.

From:

<a data-text="text">content</a> 

to:

<div data-text="text">content</div> 

Any idea?

like image 456
Michael Antonius Avatar asked Dec 13 '12 13:12

Michael Antonius


People also ask

What is tag type in HTML?

The HTML type Attribute is used to specify the type of button for <button> elements. It is also used in the <input> element to specify the type of input to display. For embed elements like link, object, script, source, and style used to specify the Internet Media Type. Syntax: <element type="value">


2 Answers

2018 Update:

Use ChildNode.replaceWith() method. As exemplified in MDN docs:

var parent = document.createElement("div"); var child = document.createElement("p"); parent.appendChild(child); var span = document.createElement("span");  child.replaceWith(span);  console.log(parent.outerHTML); // "<div><span></span></div>" 

More information in the this answer.

like image 159
Santiago M. Quintero Avatar answered Sep 21 '22 12:09

Santiago M. Quintero


No. You cannot change the tagName (nodeName) of a DOM node.

You only could create a new node of the wanted type, copy all attributes (and maybe properties) and move the child nodes. Yet you would loose inaccessible things like attached event listeners. This technique is for example used when you want to change the type of an input in IE.

However, there is absolutely no reason to change an a into a div, they have completely different semantics (also behaviour and layout).

like image 23
Bergi Avatar answered Sep 23 '22 12:09

Bergi