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:38

Working pure DOM algorithm

function rename_element(node, name) {
    let renamed = document.createElement(name);

    Array.from(node.attributes).forEach(attr => {
        renamed.setAttribute(attr.name, attr.value);        
    })
    while (node.firstChild) {
        renamed.appendChild(node.firstChild);
    }
    node.parentNode.replaceChild(renamed, node);
    return renamed;
}

查看更多
地球回转人心会变
3楼-- · 2020-01-25 06:41

The above solutions wipe out the existing element and re-create it from scratch, destroying any event bindings on children in the process.

short answer: (loses 's attributes)

$("p").wrapInner("<div/>").children(0).unwrap();

longer answer: (copies 's attributes)

$("p").each(function (o, elt) {
  var newElt = $("<div class='p'/>");
  Array.prototype.slice.call(elt.attributes).forEach(function(a) {
    newElt.attr(a.name, a.value);
  });
  $(elt).wrapInner(newElt).children(0).unwrap();
});

fiddle with nested bindings

It would be cool to copy any bindings from the at the same time, but getting current bindings didn't work for me.

查看更多
beautiful°
4楼-- · 2020-01-25 06:43

Take him by the word

Taken the Question by Word "how to change tag name?" I would suggest this solution:
If it makes sense or not has to be decided case by case.

My example will "rename" all a-Tags with hyperlinks for SMS with span tags. Maintaining all attributes and content:

$('a[href^="sms:"]').each(function(){
  var $t=$(this);
  var $new=$($t.wrap('<div>')
    .parent()
        .html()
        .replace(/^\s*<\s*a/g,'<span')
        .replace(/a\s*>\s*$/g,'span>')
        ).attr('href', null);
  $t.unwrap().replaceWith($new);
});

As it does not make any sense to have a span tag with an href attribute I remove that too. Doing it this way is bulletproof and compatible with all browsers that are supported by jquery. There are other ways people try to copy all the Attributes to the new Element, but those are not compatible with all browsers.

Although I think it is quite expensive to do it this way.

查看更多
Emotional °昔
5楼-- · 2020-01-25 06:45

You can replace any HTML markup by using jQuery's .replaceWith() method.

example: http://jsfiddle.net/JHmaV/

Ref.: .replaceWith

If you want to keep the existing markup, you could use code like this:

$('#target').replaceWith('<newTag>' + $('#target').html() +'</newTag>')
查看更多
The star\"
6楼-- · 2020-01-25 06:46

No, it is not possible according to W3C specification: "tagName of type DOMString, readonly"

http://www.w3.org/TR/DOM-Level-2-Core/core.html

查看更多
走好不送
7楼-- · 2020-01-25 06:50

Inspired by ericP answer, formatted and converted to jQuery plugin:

$.fn.replaceWithTag = function(tagName) {
    var result = [];
    this.each(function() {
        var newElem = $('<' + tagName + '>').get(0);
        for (var i = 0; i < this.attributes.length; i++) {
            newElem.setAttribute(
                this.attributes[i].name, this.attributes[i].value
            );
        }
        newElem = $(this).wrapInner(newElem).children(0).unwrap().get(0);
        result.push(newElem);
    });
    return $(result);
};

Usage:

$('div').replaceWithTag('span')
查看更多
登录 后发表回答