Raynos
Raynos

Reputation: 169373

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]

Upvotes: 8

Views: 536

Answers (2)

Esailija
Esailija

Reputation: 140210

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/

Upvotes: 2

Raynos
Raynos

Reputation: 169373

IE8 says no. :(

Seriously though, apart from hacks and assumptions there is no clean way.

As suggested in the comments you can assume comments are not doctype like

doctype.data.indexOf("<!DOCTYPE html") !== -1 && doctype.data.indexOf(">") !== -1

Or make assumptions about the DOM structure

I believe that only comment nodes, (and anything treated by the parser as a comment node, e.g. an xml declaration) can precede the doctype

So you can just loop over the comment nodes in document.childNodes until you find one that matches the above regexp.

Upvotes: 0

Related Questions