Get html tags from string javascript

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

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

Chris Martin

29.7k8 gold badges74 silver badges131 bronze badges

asked Nov 16, 2010 at 17:20

Justin StaytonJustin Stayton

5,7218 gold badges35 silver badges43 bronze badges

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);

answered Jan 29, 2013 at 22:12

posit labsposit labs

8,6004 gold badges36 silver badges59 bronze badges

1

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.

answered Sep 8, 2013 at 1:59

Get html tags from string javascript

doubleswirvedoubleswirve

1,3283 gold badges16 silver badges22 bronze badges

2

In jQuery:

var html_string = $('html').outerHTML()

In plain Javascript:

var html_string = document.documentElement.outerHTML

answered Nov 16, 2010 at 17:22

0

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

http://api.jquery.com/attr/

Additionally:

there is a jQuery plugin here: http://plugins.jquery.com/project/getAttributes

that allows you to get all attributes from an HTML element

answered Nov 16, 2010 at 17:22

bimbom22bimbom22

4,4622 gold badges30 silver badges46 bronze badges

1

I found other alternative simple way using plain javascript:

const htmlElement = document.querySelector(':root')
console.log(htmlElement)

answered Jan 23 at 12:55