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?
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">
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With