Page

[JavaScript]根据dom的nodeType过滤掉注释元素

725Anson18-02-02



function removeComment( html ) {    
    var parent = document.createElement("div");    
    parent.innerHTML = html;
    [].forEach.call(parent.childNodes, function(child) {        
        if( child.nodeType === 8 ) return parent.removeChild( child );        
        if( child.nodeType === 1 ) child.innerHTML = removeComment( child.innerHTML );
    });    
    return parent.innerHTML;
}


Node Types

文档、元素、属性以及 HTML 或 XML 文档的其他方面拥有不同的节点类型。

存在 12 种不同的节点类型,其中可能会有不同节点类型的子节点:

节点类型描述子节点
1Element代表元素Element, Text, Comment, ProcessingInstruction, CDATASection, EntityReference
2Attr代表属性Text, EntityReference
3Text代表元素或属性中的文本内容。None
4CDATASection代表文档中的 CDATA 部分(不会由解析器解析的文本)。None
5EntityReference代表实体引用。Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
6Entity代表实体。Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
7ProcessingInstruction代表处理指令。None
8Comment代表注释。None
9Document代表整个文档(DOM 树的根节点)。Element, ProcessingInstruction, Comment, DocumentType
10DocumentType向为文档定义的实体提供接口None
11DocumentFragment代表轻量级的 Document 对象,能够容纳文档的某个部分Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
12Notation代表 DTD 中声明的符号。None



函数转自:https://segmentfault.com/q/1010000002691720


来自ansion博客 

http://www.tp0.top

2018-02-02 21:20:48