Jquery取消注释head标签内的第二个孩子

时间:2017-01-18 17:45:51

标签: javascript jquery

我在head标签中有两个注释标签。我想仅取消注释第二条评论。

var x = "<html><head><!-- <#if> I don't want any change </#if> --><!-- <#if>I want to uncomment </#if> --></head></html>";

$(x).contents().each(function(index, node) {
     if (node.nodeType == 8) {
        $(node[0]).replaceWith(node.nodeValue);
    }
});

alert(x);

输出应为:

<html>
<head>
    <!-- <#if> I don't want any change </#if> -->
    <#if> I want to uncomment </#if>
<head>
</html>

1 个答案:

答案 0 :(得分:0)

也许

var x = document.getElementsByTagName("head")[0].innerHTML;

var parts = x.split("<!-- "); 
parts[2]=parts[2].replace(" -->",""); 
parts[1] = "<!-- " + parts[1]; 
document.getElementsByTagName("head")[0].innerHTML=parts.join("");