jQuery: how to change tag name?

2020-01-25 06:20发布

jQuery: how to change tag name?

For example:

<tr>
    $1
</tr>

I need

<div>
    $1
</div>

Yes, I can

  1. Create DOM element <div>
  2. Copy tr content to div
  3. Remove tr from dom

But can I make it directly?

PS:

    $(tr).get(0).tagName = "div"; 

results in DOMException.

17条回答
够拽才男人
2楼-- · 2020-01-25 06:58

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/

查看更多
祖国的老花朵
3楼-- · 2020-01-25 07:00

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:

// Define this at whatever scope you'll need to access it
// Most of these kinds of constructors are attached to the `window` object

window.HTMLBookElement = function() {

  function HTMLBookElement() {
    var book = document.createElement('book');
    book.__proto__ = document.createElement('audio');
    return book;
  }

  return new HTMLBookElement();

}

// Test your new element in a console (I'm assuming you have Chrome)

var harryPotter = new HTMLBookElement();

// You should have access to your new `HTMLBookElement` API as well as that
// of its prototype chain; since I prototyped `HTMLAudioElement`, you have 
// some default properties like `volume` and `preload`:

console.log(harryPotter);         // should log "<book></book>"
console.log(harryPotter.volume);  // should log "1"
console.log(harryPotter.preload); // should log "auto"

All DOM elements work this way. For example: <div></div> is produced by HTMLDivElement, which extends HTMLElement, which in turn extends Element, which in turn extends Object.

查看更多
别忘想泡老子
4楼-- · 2020-01-25 07:01

Jquery plugin to make "tagName" editable :

(function($){
    var $newTag = null;
    $.fn.tagName = function(newTag){
        this.each(function(i, el){
            var $el = $(el);
            $newTag = $("<" + newTag + ">");

            // attributes
            $.each(el.attributes, function(i, attribute){
                $newTag.attr(attribute.nodeName, attribute.nodeValue);
            });
            // content
            $newTag.html($el.html());

            $el.replaceWith($newTag);
        });
        return $newTag;
    };
})(jQuery);

See : http://jsfiddle.net/03gcnx9v/3/

查看更多
We Are One
5楼-- · 2020-01-25 07:01

You can use this function

var renameTag  = function renameTag($obj, new_tag) {
    var obj = $obj.get(0);
    var tag = obj.tagName.toLowerCase();
    var tag_start = new RegExp('^<' + tag);
    var tag_end = new RegExp('<\\/' + tag + '>$');
    var new_html = obj.outerHTML.replace(tag_start, "<" + new_tag).replace(tag_end, '</' + new_tag + '>');
    $obj.replaceWith(new_html);
};

ES6

const renameTag = function ($obj, new_tag) {
    let obj = $obj.get(0);
    let tag = obj.tagName.toLowerCase();
    let tag_start = new RegExp('^<' + tag);
    let tag_end = new RegExp('<\\/' + tag + '>$');
    let new_html = obj.outerHTML.replace(tag_start, "<" + new_tag).replace(tag_end, '</' + new_tag + '>');
    $obj.replaceWith(new_html);
};

Sample code

renameTag($(tr),'div');
查看更多
SAY GOODBYE
6楼-- · 2020-01-25 07:03

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

  1. createElement(new_name)
  2. copy all content to new element;
  3. replace old to new by replaceChild()

is something like this,

function rename_element(node,name) {
    var renamed = document.createElement(name); 
    foreach (node.attributes as a) {
        renamed.setAttribute(a.nodeName, a.nodeValue);
    }
    while (node.firstChild) {
        renamed.appendChild(node.firstChild);
    }
    return node.parentNode.replaceChild(renamed, node);
}

... wait review and jsfiddle ...

jQuery algorithm

The @ilpoldo algorithm is a good start point,

   $from.replaceWith($('<'+newname+'/>').html($from.html()));

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

查看更多
登录 后发表回答