Search code examples
javascripthtmltags

Method to change self-closing tags to explicit tags in Javascript?


Does there exist a method or function that can convert the self-closing tags to explicit tags in Javascript? For example:

<span class="label"/>

converted to :

<span class ="label"></span>

I would like to copy a new HTML from the iframe to the outerHTML of the main page, as the new HTML generated contains self-closing tags, the outerHTML doesn't recognize them and then doesn't change and the page doesn't show correctly. But when the format is standard, that is,with the non-self-closing tags, the outerHTML will take the new HTML,and the page shows perfectly.This is why I would like to change the tags.


And this html is in a string

In fact, I don't want to parse HTML, I just want to find the "< span.../>"and replace it with "< span...>< /span>"


Solution

  • Thanks all, I finally use the silly method to change the self-closing tags, maybe it'll help someone like me:

    var splitSpan = textHTML.split(">");
    var i=0;
    for(i=0;i<splitSpan.length-1;i++){
        var lengthSpan = splitSpan[i].length;
        var subSpan = splitSpan[i].substring(1,5);
        var endSpan = splitSpan[i].charAt(lengthSpan-1);
        
        if(subSpan=="span" && endSpan=="/")
        {           
            splitSpan[i]=setCharAt(splitSpan[i],lengthSpan-1,'>');
            splitSpan[i]=splitSpan[i]+"</span>";
        }
        else
        {
            splitSpan[i]=splitSpan[i]+">";
        }
    }
    

    function setCharAt(str,index,chr) {
        if(index > str.length-1) return str;
        return str.substr(0,index) + chr + str.substr(index+1);
    }