Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the <html> tag HTML with JavaScript / jQuery?

People also ask

How do I get HTML using jQuery?

To get HTML content of an element using jQuery, use the html() method. The html() method gets the html contents of the first matched element.

How do I get HTML using JavaScript?

Get HTML elements by TagName: In javascript, getElementsByTagName() method is useful to access the HTML elements using the tag name. This method is the same as the getElementsByName method. Here, we are accessing the elements using the tag name instead of using the name of the element.

What is HTML () in jQuery?

jQuery | html() Method The html() Method in jQuery is used to set or return the innerHTML content of the selected element. Syntax: It returns the content of first matched element. $(selector).html() It sets the content of matched element.

How HTML elements are used in jQuery with example?

The html() method in jQuery is used to get the contents of the first element in the set of matched elements or is used to set the HTML contents of every matched element. It returns the content of the first matched element. This function does not accept any arguments.


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

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