replace specific tag name javascript

前端 未结 5 1424
清酒与你
清酒与你 2020-12-29 16:07

I want to know if we can change tag name in a tag rather than its content. i have this content

< wns id=\"93\" onclick=\"wish(id)\">...< /wns>           


        
5条回答
  •  悲哀的现实
    2020-12-29 16:52

    You can't change the tag name of an existing DOM element; instead, you have to create a replacement and then insert it where the element was.

    The basics of this are to move the child nodes into the replacement and similarly to copy the attributes. So for instance:

    var wns = document.getElementById("93");
    var lmn = document.createElement("lmn");
    var index;
    
    // Copy the children
    while (wns.firstChild) {
        lmn.appendChild(wns.firstChild); // *Moves* the child
    }
    
    // Copy the attributes
    for (index = wns.attributes.length - 1; index >= 0; --index) {
        lmn.attributes.setNamedItem(wns.attributes[index].cloneNode());
    }
    
    // Replace it
    wns.parentNode.replaceChild(lmn, wns);
    

    Live Example: (I used div and p rather than wns and lmn, and styled them via a stylesheet with borders so you can see the change)

    document.getElementById("theSpan").addEventListener("click", function() {
      alert("Span clicked");
    }, false);
    
    document.getElementById("theButton").addEventListener("click", function() {
    
      var wns = document.getElementById("target");
      var lmn = document.createElement("p");
      var index;
    
      // Copy the children
      while (wns.firstChild) {
        lmn.appendChild(wns.firstChild); // *Moves* the child
      }
    
      // Copy the attributes
      for (index = wns.attributes.length - 1; index >= 0; --index) {
        lmn.attributes.setNamedItem(wns.attributes[index].cloneNode());
      }
    
      // Insert it
      wns.parentNode.replaceChild(lmn, wns);
    }, false);
    div {
      border: 1px solid green;
    }
    p {
      border: 1px solid blue;
    }
    Content before span in the middle Content after

    See this gist for a reusable function.


    Side note: I would avoid using id values that are all digits. Although they're valid in HTML (as of HTML5), they're invalid in CSS and thus you can't style those elements, or use libraries like jQuery that use CSS selectors to interact with them.

提交回复
热议问题