简体   繁体   中英

How to detect if an HTML5 valid doctype is present in the document using JavaScript?

I was wondering if there was just simply a way to detect if a doctype is present - preferably an HTML5 doctype only. I don't want to return it in a string or anything (though I have already tried this with similar questions being asked here, see code below), rather, I just want to see if it doesn't exist. Like, if it is absent, call an alert , then return false , or if it is present, call an acceptance function.

Like I said previously, I have read other posts on here and other posts on other forums but none of them seem to match my answer, or maybe I'm interpreting the code incorrectly, if so please tell me.

The code I have already tried goes as follows:

    var msg = {
        noHTML5: "You're pages document type is either not defined or not compliant with HTML5."
    },

    node = document.doctype,
    thisNodeHTML = "<!DOCTYPE " + node.name + (node.publicId ? ' PUBLIC"' + node.publicId + '"' : '') + (!node.publicId && node.systemId ? ' SYSTEM' : '') + (node.systemId ? ' "' + node.systemId + '"' : '') + ">";

    if(!thisNodeHTML) {
        alert(msg.noHTML5);

        return false;
    }

    else {
       // success = true;
    }

Edit:

I did notice, however, that once I took away the doctype in my html file, Chrome's error console catches it and displays an error. Maybe does my conditional statement have an incorrect syntax?

document.doctype is null when no doctype is present, thus your error. Tweak your method to return false in this condition, and you should be good. Sample detection function, based on the doctype:

var is_html5 = function () {
    if (document.doctype === null) return false;

    var node = document.doctype;
    var doctype_string = "<!DOCTYPE " + node.name + (node.publicId ? ' PUBLIC"' + node.publicId + '"' : '') + (!node.publicId && node.systemId ? ' SYSTEM' : '') + (node.systemId ? ' "' + node.systemId + '"' : '') + ">";

    return doctype_string === '<!DOCTYPE html>';
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM