How to verify that the document markup is HTML5?

Asked

Viewed 335 times

7

I am creating a plugin and need to know if the document is written in HTML5 or not.

I thought I’d use the document.doctype, but I don’t know what to compare it to since I compare it to '<!DOCTYPE html>' returns false, because the same is a node and not text.

How can I do that?

2 answers

3


Already tried to turn the object into a string ?

var objSerializer = new XMLSerializer();
var doctypeName   = objSerializer.serializeToString(document.doctype);

console.log(doctypeName);

Then you can make the comparison.

if(doctypeName == "<!DOCTYPE html>"){
    console.log('É HTML 5');
}
  • 1

    All right, it worked perfectly.

1

Whereas HTML5 documents are declared in the block early with: <!DOCTYPE html>, in addition to them there are the old versions as demonstrated at this address:

https://www.totalvalidator.com/support/doctypes.html

If as a rule the HTML5 document does not receive versioning, it means that a systemId or a publicId declared in its block and that is different from: SYSTEM "about:legacy-compat". And that this document contains a type of doctype defined by <!DOCTYPE html> or <!doctype html>, we can make the following check:

 function checkHTML5() {
    var isHtml5 = document.doctype.nodeName;
    var systemId = document.doctype.systemId;
    var publicId = document.publicId;
    var xmlSerializer = new XMLSerializer();
    var doctypeHTML   = xmlSerializer.serializeToString(document.doctype);
    var doctypeName   = doctypeHTML.toLowerCase();
            if (isHtml5 == "html"                            &&
               (systemId == undefined                        ||
                systemId.indexOf("about:legacy-compat")!==-1 ||
                systemId == '')                              && 
                publicId == undefined                        ||
                publicId == ''                               &&
                doctypeName.indexOf("!doctype") !== -1) {
               return true;   
            }
    console.log(publicId);
    return false;
}
checkHTML5();
  • 1

    I tested here on the console itself and it did not work, returned false...

  • There really was a mistake, because the exit systemId can be both empty and undefined, This depends on the doctype settings, but thank you for warning me about the bug.

  • Now you’re right.. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.