Change node type

前端 未结 4 1615
广开言路
广开言路 2021-01-05 03:44

Using jQuery, is it possible to change all matched elements to a different type?

For example, can I select all a tags, $(\"a\"), and change

相关标签:
4条回答
  • 2021-01-05 04:16

    No, you can't actually change it, but you can replace them with a new element using the replaceWith() method:

    $("a").replaceWith("<input>");
    

    If there are any attributes that you want to keep, you'll need to manually set them:

    $("a").replaceWith(function() {
        return $("<input>", {
            class: this.className,
            value: this.innerHTML
        });
    });
    
    0 讨论(0)
  • 2021-01-05 04:17
    $("a").each( function() {
        this.replaceWith( $("<input>").html( this.innerHTML() ) );
    });
    
    0 讨论(0)
  • 2021-01-05 04:22

    Using standard JavaScript's ChildNode.replaceWith() method can do this. Run example.

    var element = document.querySelector("span");
    var elementInnerHTML = element.innerHTML;
    var newElement = document.createElement("h1");
    newElement.innerHTML = elementInnerHTML;
    
    element.replaceWith(newElement);
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>hightekk.com</title>
    </head>
    <body>
      <span>
        Hello World
      </span>
    </body>
    </html>

    0 讨论(0)
  • 2021-01-05 04:35

    Changing an A element to an INPUT element isn't changing the type, it is changing the tagName. According to the DOM 2 Core specification, an element's tagName is readonly, so no, you can't set it.

    However, you can replace an element with a different element, provided it is valid in the DOM.

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