Each web page loaded in the browser has its own document object. The Document interface serves as an entry point into the web page's content (the DOM tree, including elements such as <body> and <table>) and provides functionality which is global to the document (such as obtaining the page's URL and creating new elements in the document).
A document object can be obtained from various APIs:
- Most commonly, you work with the document the script is running in by using
documentin document's scripts. (The same document can also be referred to aswindow.document.) - The document of an iframe via the iframe's
contentDocumentproperty. - The
responseXMLof anXMLHttpRequestobject. - The document that a given node or element belongs to can be retrieved using the node's
ownerDocumentproperty.
Depending on the kind of the document (e.g. HTML or XML), different APIs may be available on the document object.
- All document objects implement the
Documentinterface (and hence theNodeandEventTargetinterfaces). Thus, the "core" properties and methods documented on this page are available for all kinds of documents. - In contemporary browsers, some documents (e.g. those served with the
text/htmlcontent type) also implement theHTMLDocumentinterface. - In contemporary browsers, SVG documents implement the
SVGDocumentinterface.
In the future, all those interfaces will be collapsed into the Document interface.
Properties
Note: The Document interface also inherits from the Node and EventTarget interfaces.
document.all- Provides access to all elements with an
id. This is a legacy, non-standard, interface and you should use thedocument.getElementById()method instead. document.async- Used with
document.loadto indicate an asynchronous request. document.characterSet- Returns the character set being used by the document.
document.compatMode- Indicates whether the document is rendered in Quirks or Strict mode.
document.contentType- Returns the Content-Type from the MIME Header of the current document.
document.doctype- Returns the Document Type Definition (DTD) of the current document.
document.documentElement- Returns the Element that is a direct child of the document. For HTML documents, this is normally the HTML element.
document.documentURI- Returns the document location as a string.
document.domConfig- Should return a
DOMConfigurationobject. document.implementation- Returns the DOM implementation associated with the current document.
document.inputEncoding- Returns the encoding used when the document was parsed.
document.lastStyleSheetSet- Returns the name of the style sheet set that was last enabled. Has the value
nulluntil the style sheet is changed by setting the value ofselectedStyleSheetSet. document.mozSyntheticDocumenttrueif this document is synthetic, such as a standalone image, video, audio file, or the like.document.mozFullScreentruewhen the document is infull-screen mode.document.mozFullScreenElement- The element that's currently in full screen mode for this document.
document.mozFullScreenEnabledtrueif callingelement.mozRequestFullscreen()would succeed in the curent document.document.pointerLockElement- Returns the element set as the target for mouse events while the pointer is locked.
nullif lock is pending, pointer is unlocked, or if the target is in another document. document.preferredStyleSheetSet- Returns the preferred style sheet set as specified by the page author.
document.scrollingElementRead only- Returns a reference to the
Elementthat scrolls the document. document.selectedStyleSheetSet- Returns which style sheet set is currently in use.
document.styleSheets- Returns a list of the style sheet objects on the current document.
document.styleSheetSets- Returns a list of the style sheet sets available on the document.
document.xmlEncoding- Returns the encoding as determined by the XML declaration.
document.xmlStandaloneObsolete since Gecko 10.0- Returns
trueif the XML declaration specifies the document to be standalone (e.g., An external part of the DTD affects the document's content), elsefalse. document.xmlVersionObsolete since Gecko 10.0- Returns the version number as specified in the XML declaration or
"1.0"if the declaration is absent.
The Document interface is extended with the ParentNode interface:
ParentNode.childrenRead only- Returns a live
HTMLCollectioncontaining all objects of typeElementthat are children of thisParentNode. ParentNode.firstElementChildRead only- Returns the
Elementthat is the first child of thisParentNode, ornullif there is none. ParentNode.lastElementChildRead only- Returns the
Elementthat is the last child of thisParentNode, ornullif there is none. ParentNode.childElementCountRead only- Returns an
unsigned longgiving the amount of children that the object has.
Extension for HTML document
The Document interface for HTML documents inherit from the HTMLDocument interface or, since HTML5, is extended for such documents:
document.activeElement- Returns the currently focused element.
document.alinkColor- Returns or sets the color of active links in the document body.
document.anchors- Returns a list of all of the anchors in the document.
document.applets- Returns an ordered list of the applets within a document.
document.bgColor- Gets/sets the background color of the current document.
document.body- Returns the
<body>element of the current document. document.cookie- Returns a semicolon-separated list of the cookies for that document or sets a single cookie.
document.defaultView- Returns a reference to the window object.
document.designMode- Gets/sets the ability to edit the whole document.
document.dir- Gets/sets directionality (rtl/ltr) of the document.
document.domain- Returns the domain of the current document.
document.embeds- Returns a list of the embedded
<embed>elements within the current document. document.fgColor- Gets/sets the foreground color, or text color, of the current document.
document.forms- Returns a list of the
<form>elements within the current document. document.head- Returns the
<head>element of the current document. document.height- Gets/sets the height of the current document.
document.images- Returns a list of the images in the current document.
document.lastModified- Returns the date on which the document was last modified.
document.linkColor- Gets/sets the color of hyperlinks in the document.
document.links- Returns a list of all the hyperlinks in the document.
document.location- Returns the URI of the current document.
document.plugins- Returns a list of the available plugins.
document.readyState- Returns loading status of the document.
document.referrer- Returns the URI of the page that linked to this page.
document.scripts- Returns all the
<script>elements on the document. document.title- Returns the title of the current document.
document.URLRead only- Returns the document location as a string.
document.vlinkColor- Gets/sets the color of visited hyperlinks.
document.width- Returns the width of the current document.
Event handlers
document.onpointerlockchange- Returns the event handling code for the
pointerlockchangeevent. document.onpointerlockerror- Returns the event handling code for the
pointerlockerrorevent. document.onreadystatechange- Returns the event handling code for the
readystatechangeevent.
Methods
Note: The Document interface also inherits from the Node and EventTarget interfaces.
document.adoptNode(Node node)- Adopt node from an external document.
document.captureEvents(String eventName)- See
window.captureEvents. document.caretPositionFromPoint(Number x, Number y)- Gets the
CaretPositionat or near the specified coordinates. document.caretRangeFromPoint(Number x, Number y)- Gets a
Rangeobject for the document fragment under the specified coordinates. document.createAttribute(String name)- Creates a new
Attrobject and returns it. document.createAttributeNS(String namespace, String name)- Creates a new attribute node in a given namespace and returns it.
document.createCDATASection(String data)- Creates a new CDATA node and returns it.
document.createComment(String comment)- Creates a new comment node and returns it.
document.createDocumentFragment()- Creates a new document fragment.
document.createElement(String name)- Creates a new element with the given tag name.
document.createElementNS(String namespace, String name)- Creates a new element with the given tag name and namespace URI.
document.createEntityReference(String name)- Creates a new entity reference object and returns it.
document.createEvent(String interface)- Creates an event object.
document.createNodeIterator(Node root[, Number whatToShow[, NodeFilter filter]])- Creates a
NodeIteratorobject. document.createProcessingInstruction(String target, String data)- Creates a new
ProcessingInstructionobject. document.createRange()- Creates a
Rangeobject. document.createTextNode(String text)- Creates a text node.
document.createTreeWalker(Node root[, Number whatToShow[, NodeFilter filter]])- Creates a
TreeWalkerobject. document.elementFromPoint(Number x, Number y)- Returns the topmost element at the specified coordinates.
document.elementsFromPoint(Number x, Number y)- Returns an array of all elements at the specified coordinates.
document.enableStyleSheetsForSet(String name)- Enables the style sheets for the specified style sheet set.
document.exitPointerLock()- Release the pointer lock.
document.getElementsByClassName(String className)- Returns a list of elements with the given class name.
document.getElementsByTagName(String tagName)- Returns a list of elements with the given tag name.
document.getElementsByTagNameNS(String namespace, String tagName)- Returns a list of elements with the given tag name and namespace.
document.importNode(Node node, Boolean deep)- Returns a clone of a node from an external document.
document.normalizeDocument()- Replaces entities, normalizes text nodes, etc.
document.releaseCapture()- Releases the current mouse capture if it's on an element in this document.
document.releaseEvents- See
window.releaseEvents. document.routeEventObsolete since Gecko 24- See
window.routeEvent. document.mozSetImageElement- Allows you to change the element being used as the background image for a specified element ID.
The Document interface is extended with the ParentNode interface:
document.getElementById(String id)- Returns an object reference to the identified element.
document.querySelector(String selector)- Returns the first Element node within the document, in document order, that matches the specified selectors.
document.querySelectorAll(String selector)- Returns a list of all the Element nodes within the document that match the specified selectors.
The Document interface is extended with the XPathEvaluator interface:
document.createExpression(String expression, XPathNSResolver resolver)- Compiles an
XPathExpressionwhich can then be used for (repeated) evaluations. document.createNSResolver(Node resolver)- Creates an
XPathNSResolverobject. document.evaluate(String expression, Node contextNode, XPathNSResolver resolver, Number type, Object result)- Evaluates an XPath expression.
Extension for HTML documents
The Document interface for HTML documents inherit from the HTMLDocument interface or, since HTML5, is extended for such documents:
document.clear()- In majority of modern browsers, including recent versions of Firefox and Internet Explorer, this method does nothing.
document.close()- Closes a document stream for writing.
document.execCommand(String command[, Boolean showUI[, String value]])- On an editable document, executes a formating command.
document.getElementsByName(String name)- Returns a list of elements with the given name.
document.getSelection()- Returns a
Selectionobject related to text selected in the document. document.hasFocus()- Returns
trueif the focus is currently located anywhere inside the specified document. document.open()- Opens a document stream for writing.
document.queryCommandEnabled(String command)- Returns true if the formating command can be executed on the current range.
document.queryCommandIndeterm(String command)- Returns true if the formating command is in an indeterminate state on the current range.
document.queryCommandState(String command)- Returns true if the formating command has been executed on the current range.
document.queryCommandSupported(String command)- Returns true if the formating command is supported on the current range.
document.queryCommandValue(String command)- Returns the current value of the current range for a formating command.
document.write(String text)- Writes text in a document.
document.writeln(String text)- Writes a line of text in a document.
Specifications
Browser compatibility notes
Firefox notes
Mozilla defines a set of non-standard properties made only for XUL content:
document.currentScript- Returns the
<script>element that is currently executing. document.documentURIObject- (Mozilla add-ons only!) Returns the
nsIURIobject representing the URI of the document. This property only has special meaning in privileged JavaScript code (with UniversalXPConnect privileges). document.popupNode- Returns the node upon which a popup was invoked.
document.tooltipNode- Returns the node which is the target of the current tooltip.
Mozilla also define some non-standard methods:
document.execCommandShowHelpObsolete since Gecko 14.0- This method never did anything and always threw an exception, so it was removed in Gecko 14.0 (Firefox 14.0 / Thunderbird 14.0 / SeaMonkey 2.11).
document.getBoxObjectFor- Use the
Element.getBoundingClientRect()method instead. document.loadOverlay- Loads a XUL overlay dynamically. This only works in XUL documents.
document.queryCommandTextObsolete since Gecko 14.0- This method never did anything but throw an exception, and was removed in Gecko 14.0 (Firefox 14.0 / Thunderbird 14.0 / SeaMonkey 2.11).
Internet Explorer notes
Microsoft defines some non-standard properties:
document.fileSize*- Returns size in bytes of the document. Starting with Internet Explorer 11, that property is no longer supported. See MSDN.
- Internet Explorer does not support all methods from the
Nodeinterface in theDocumentinterface:
document.contains- As a work-around,
document.body.contains()can be used.