Skip to content
Advertisement

How to get the tag HTML with JavaScript / jQuery?

Using $('html').html() I can get the HTML within the <html> tag (<head>, <body>, etc.). But how can I get the actual HTML of the <html> tag (with attributes)?

Alternatively, is it possible to get the entire HTML of the page (including doctype, <html>, etc.) with jQuery (or plain old JavaScript)?

Advertisement

Answer

The simplest way to get the html element natively is:

document.documentElement

Here’s the reference: https://developer.mozilla.org/en-US/docs/Web/API/Document.documentElement.

UPDATE: To then grab the html element as a string you would do:

document.documentElement.outerHTML
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement