replace specific tag name javascript

前端 未结 5 1432
清酒与你
清酒与你 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

    There are several problems with your code:

    1. HTML element IDs must start with an alphabetic character.
    2. document.getElementById("99").replace(/wns/g,"lmn") is effectively running a replace command on an element. Replace is a string method so this causes an error.
    3. You're trying to assign this result to document.getElementById("99").innerHTML, which is the HTML inside the element (the tags, attributes and all are part of the outerHTML).
    4. You can't change an element's tagname dynamically, since it fundamentally changes it's nature. Imagine changing a textarea to a select… There are so many attributes that are exclusive to one, illegal in the other: the system cannot work!

    What you can do though, is create a new element, and give it all the properties of the old element, then replace it:

    
        ...
    
    

    Using the following script:

    // Grab the original element
    var original    = document.getElementById('e93');
    // Create a replacement tag of the desired type
    var replacement = document.createElement('lmn');
    
    // Grab all of the original's attributes, and pass them to the replacement
    for(var i = 0, l = original.attributes.length; i < l; ++i){
        var nodeName  = original.attributes.item(i).nodeName;
        var nodeValue = original.attributes.item(i).nodeValue;
    
        replacement.setAttribute(nodeName, nodeValue);
    }
    
    // Persist contents
    replacement.innerHTML = original.innerHTML;
    
    // Switch!
    original.parentNode.replaceChild(replacement, original);
    

    Demo here: http://jsfiddle.net/barney/kDjuf/

提交回复
热议问题