Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a DOM Node is the node representing the doctype declaration?

So let's say (in IE8) that we have a document.

Now normally we can assume that document.childNodes[0] is the doctype. So

var doctype = document.childNodes[0]

Now how do we confirm rather then assume it is the doctype?

doctype.nodeType === Node.COMMENT_NODE;
doctype.tagName === "!"; // same as a comment
doctype.data.indexOf("DOCTYPE ") > -1; // same as any comment containing the word DOCTYPE.
doctype === document.doctype; // false, document.doctype is undefined in IE8

Apart from assumptions, how am I supposed to know whether a given node is a doctype?

For those of you unfamiliar with DOM4 take a look at DocumentType

The DOM-shim get's document.doctype in IE8 by just returning document.childNodes[0]

like image 451
Raynos Avatar asked Oct 28 '11 18:10

Raynos


People also ask

Is document a DOM node?

The DOM represents the document as nodes and objects; that way, programming languages can interact with the page. A web page is a document that can be either displayed in the browser window or as the HTML source.

What do the nodes in the DOM represent?

Nodes are in the DOM aka Document Object model. In the DOM, all parts of the document, such as elements, attributes, text, etc. are organized in a hierarchical tree-like structure; consisting of parents and children. These individual parts of the document are known as nodes.

What is the node type of document node?

Node Types Document Node − Complete XML document structure is a document node. Element Node − Every XML element is an element node. This is also the only type of node that can have attributes. Attribute Node − Each attribute is considered an attribute node.

Is DOM tree node represents an element?

The DOM views an HTML document as a tree of nodes. A node represents an HTML element. Let's take a look at this HTML code to better understand the DOM tree structure. Our document is called the root node and contains one child node which is the <html> element.


1 Answers

I figured out that in IE7 and IE8 the .innerHTML property for comments is always the full "<!--comment here-->" and for the doctype node, it is "". Even for empty comments, the .innerHTML is "<!---->"

So based on this I created:

function isDocType(node) {
    return node && (
    node.nodeType === 10 || (node.nodeType === 8 && "innerHTML" in node && node.innerHTML === ""));
}

With the test page:

<!-- comment1 -->
<!-- comment2 -->
<!---->
<!-- -->
<!-- <!DOCTYPE html> -->

Running doctype and the comments through isDocType gives:

LOG: true 
LOG: false 
LOG: false 
LOG: false 
LOG: false 
LOG: false

See http://jsfiddle.net/AEYt4/

like image 103
Esailija Avatar answered Sep 28 '22 08:09

Esailija