开发者

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

Does there exist a method or function that can convert the s开发者_Python百科elf-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>"


try this to replace all self closing tags out of your string (xml/html)

function removeSelfClosingTags(xml) {
    var split = xml.split("/>");
    var newXml = "";
    for (var i = 0; i < split.length - 1;i++) {
        var edsplit = split[i].split("<");
        newXml += split[i] + "></" + edsplit[edsplit.length - 1].split(" ")[0] + ">";
    }
    return newXml + split[split.length-1];
}


I'd use regex:

var spansFixed = htmlString.replace(/<span(.*)\/>/g, '<span$1></span>');


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);
}


I can't think of any need for this, as they will automatically be converted by the browser. This can be demonstrated by:

var div = document.createElement('div');
div.innerHTML = '<span/>';
var span = div.getElementsByTagName('span')[0];
span.innerHTML = 'hello';
alert(span.innerHTML);

Edit: It seems this will only work only in XML mode.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜