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 input
s?
A node type is a collection of an application's nodes that share a common business purpose. Use node types to define nodes' properties and to define rules that convert a node type to another node type. Each node is a member of a node type.
The read-only nodeType property of a Node interface is an integer that identifies what the node is. It distinguishes different kind of nodes from each other, such as elements , text and comments .
Node Types Document Node − Complete XML document structure is a document node. Element Node − Every XML element is an element node. This is also the only type of node that can have attributes. Attribute Node − Each attribute is considered an attribute node.
Definition and Usage The nodeValue property sets or returns the value of a node. If the node is an element node, the nodeValue property will return null. Note: If you want to return the text of an element, remember that text is always inside a Text node, and you will have to return the Text node's node value (element.
No, you can't actually change it, but you can replace them with a new element using the replaceWith()
method:
$("a").replaceWith("<input>");
If there are any attributes that you want to keep, you'll need to manually set them:
$("a").replaceWith(function() {
return $("<input>", {
class: this.className,
value: this.innerHTML
});
});
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>
Changing an A element to an INPUT element isn't changing the type, it is changing the tagName. According to the DOM 2 Core specification, an element's tagName is readonly, so no, you can't set it.
However, you can replace an element with a different element, provided it is valid in the DOM.
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