Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change node type

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?

like image 607
esqew Avatar asked Jul 18 '11 03:07

esqew


People also ask

What is a node type?

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.

What is type node in Javascript?

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 .

What is node type of document node?

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.

What is nodeValue?

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.


3 Answers

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
    });
});
like image 143
user113716 Avatar answered Oct 25 '22 18:10

user113716


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>
like image 31
Ronnie Royston Avatar answered Oct 25 '22 20:10

Ronnie Royston


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.

like image 32
RobG Avatar answered Oct 25 '22 19:10

RobG