jQuery: how to change tag name?

前端 未结 17 877
無奈伤痛
無奈伤痛 2020-11-28 07:37

jQuery: how to change tag name?

For example:


    $1

I need

$1
<
相关标签:
17条回答
  • 2020-11-28 08:21

    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.

    0 讨论(0)
  • 2020-11-28 08:24

    Yet another script to change the node name

    function switchElement() {
      $element.each(function (index, oldElement) {
        let $newElement = $('<' + nodeName + '/>');
        _.each($element[0].attributes, function(attribute) {
          $newElement.attr(attribute.name, attribute.value);
        });
        $element.wrapInner($newElement).children().first().unwrap();
      });
    }
    

    http://jsfiddle.net/rc296owo/5/

    It will copy over the attributes and inner html into a new element and then replace the old one.

    0 讨论(0)
  • 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;
    }
    
    
    0 讨论(0)
  • 2020-11-28 08:27

    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>')
    
    0 讨论(0)
  • 2020-11-28 08:28

    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.

    0 讨论(0)
  • 2020-11-28 08:29

    To replace the internal contents of multiple tags, each with their own original content, you have to use .replaceWith() and .html() differently:

    http://jsfiddle.net/kcrca/VYxxG/

    0 讨论(0)
提交回复
热议问题