jQuery: how to change tag name?

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

jQuery: how to change tag name?

For example:


    $1

I need

$1
<
相关标签:
17条回答
  • 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')
    
    0 讨论(0)
  • 2020-11-28 08:38

    $(function(){
        $('#switch').bind('click', function(){
            $('p').each(function(){
            	$(this).replaceWith($('<div/>').html($(this).html()));
            });
        });
    });
    p {
        background-color: red;
    }
    
    div {
        background-color: yellow;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p>Hello</p>
    <p>Hello2</p>
    <p>Hello3</p>
    <button id="switch">replace</button>

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

    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/

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

    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

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

    Since replaceWith() didn't work for me on an element basis (maybe because I used it inside map()), I did it by creating a new element and copying the attributes as needed.

    $items = $('select option').map(function(){
    
      var
        $source = $(this),
        $copy = $('<li></li>'),
        title = $source.text().replace( /this/, 'that' );
    
      $copy
        .data( 'additional_info' , $source.val() )
        .text(title);
    
      return $copy;
    });
    
    $('ul').append($items);
    
    0 讨论(0)
提交回复
热议问题