Why do view source and inspect element look different?


View source is the string representation of HTML file where as DOM is structure in memory. DOM parses HTML file and creates DOM structure of HTML file. They are not the same thing.


Let me illustrate with example.

In this HTML file there are no header and body elements but if you inspect it on browser they are present.

This is because head and tags are compulsory for DOM but for HTML. They are optional. 

So even though there are no <html>, <head> and <body> elements in HTML file, DOM will add them in DOM structure.

Browsers can also inject plugins in DOM leading to differences in view source and inspect content.

Remember that
HTML file does not always stay in sync with DOM so any changes in DOM tree may not be appear in HTML file.

This is why view source code and inspect element look different sometimes.