jQuery: how to change tag name?
For example:
<tr>
$1
</tr>
I need
<div>
$1
</div>
Yes, I can
- Create DOM element <div>
- Copy tr content to div
- Remove tr from dom
But can I make it directly?
PS:
$(tr).get(0).tagName = "div";
results in DOMException
.
To preserve the internal content of the tag you can use the accessor
.html()
in conjunction with.replaceWith()
forked example: http://jsfiddle.net/WVb2Q/1/
Simply changing the property values won't do it (as others have said, some
HTMLElement
properties are read-only; also some hold prototypal context to more primitive elements). The closest thing you can get to mimicking the DOM API is to mimic also the process of prototypal inheritance in JavaScript.'Setting' on an object's prototype via
__proto__
is generally frowned upon. Also, you might consider why you think you need to duplicate the entire DOM element in the first place. But here goes:All DOM elements work this way. For example:
<div></div>
is produced byHTMLDivElement
, which extendsHTMLElement
, which in turn extendsElement
, which in turn extendsObject
.Jquery plugin to make "tagName" editable :
See : http://jsfiddle.net/03gcnx9v/3/
You can use this function
ES6
Sample code
Where the DOM renameNode() Method?
Today (2014) no browser understand the new DOM3 renameNode method (see also W3C) check if run at your bowser: http://jsfiddle.net/k2jSm/1/
So, a DOM solution is ugly and I not understand why (??) jQuery not implemented a workaround?
pure DOM algorithm
createElement(new_name)
replaceChild()
is something like this,
... wait review and jsfiddle ...
jQuery algorithm
The @ilpoldo algorithm is a good start point,
As others commented, it need a attribute copy ... wait generic ...
specific for
class
, preserving the attribute, see http://jsfiddle.net/cDgpS/See also https://stackoverflow.com/a/9468280/287948