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)?
This question is related to
javascript
jquery
This is how to get the html DOM element purely with JS:
var htmlElement = document.getElementsByTagName("html")[0];
or
var htmlElement = document.querySelector("html");
And if you want to use jQuery to get attributes from it...
$(htmlElement).attr(INSERT-ATTRIBUTE-NAME);
In addition to some of the other answers, you could also access the HTML element via:
var htmlEl = document.body.parentNode;
Then you could get the inner HTML content:
var inner = htmlEl.innerHTML;
Doing so this way seems to be marginally faster. If you are just obtaining the HTML element, however, document.body.parentNode
seems to be quite a bit faster.
After you have the HTML element, you can mess with the attributes with the getAttribute
and setAttribute
methods.
For the DOCTYPE, you could use document.doctype
, which was elaborated upon in this question.
In jQuery:
var html_string = $('html').outerHTML()
In plain Javascript:
var html_string = document.documentElement.outerHTML
if you want to get an attribute of an HTML element with jQuery you can use .attr();
so $('html').attr('someAttribute');
will give you the value of someAttribute
of the element html
there is a jQuery plugin here: http://plugins.jquery.com/project/getAttributes
that allows you to get all attributes from an HTML element
Source: Stackoverflow.com