Change node type

Viewed 12776

Using jQuery, is it possible to change all matched elements to a different type?

For example, can I select all a tags, $("a"), and change them to inputs?

4 Answers

Using standard JavaScript's ChildNode.replaceWith() method can do this. Run example.

var element = document.querySelector("span");
var elementInnerHTML = element.innerHTML;
var newElement = document.createElement("h1");
newElement.innerHTML = elementInnerHTML;

element.replaceWith(newElement);
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>hightekk.com</title>
</head>
<body>
  <span>
    Hello World
  </span>
</body>
</html>

Related