Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

frontend - Why do we need a <html> tag if we have <!DOCTYPE html>?

Why do we need to add the <html> tag if we have already defined that this document is html using <!DOCTYPE html> tag?

Is there any other tag that can be added instead of ?

If not, why do we need it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

On the semantic level...

<!DOCTYPE html> and <html>, despite both containing < angle brackets >, are fundamentally different things:

  • <!DOCTYPE html> declares the document type and is not parsed to any DOM elements. To quote MDN's Doctype article, "Its sole purpose is to prevent a browser from switching into so-called "quirks mode" when rendering a document".
  • <html>, however, does parse to a DOM element. You can attach attributes to it or manipulate it with JavaScript. For example, try pasting this in your browser console: document.querySelector('html').style.opacity = '0.5'. You can do that with <html>, but not with DOCTYPE.

On the spec level...

Why have any standards at all? Standards are necessary so that implementers (e.g. browser vendors) know what they need to build, and developers know what they're developing against. Without common standards, it'd be impossible to ever build interoperable software.

You can certainly question the logic of why standards were set the way they were set, and the answer almost ends up at "because history" (and sometimes "because politics"). If those historical decisions were changed now, it'd break the Web.

On the markup level...

It's best practice to always set a lang attribute on the HTML element, for accessibility and SEO reasons, and you need to include it in order to do that:

Always use a language attribute on the html tag to declare the default language of the text in the page.

It's also a general best practice when writing code or markup to be explicit with what you intend, to help others reading your work. For that reason alone, it's clearer to add a surrounding HTML tag.

On the DOM level...

If you don't include any attributes on the HTML element, it doesn't actually matter what you write in terms of how it's parsed, because HTML is quite forgiving) (credit @Run_Script for the link). It'll get parsed out to the relevant DOM nodes anyway, so document.body.parentElement instanceof HTMLHtmlElement will always be true.

Still, for the reasons laid out above, I'd recommend always including it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...