Document
Baseline Widely available *
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
* Some parts of this feature may have varying levels of support.
TheDocument interface represents any web page loaded in the browser and serves as an entry point into the web page's content, which is theDOM tree.
The DOM tree includes elements such as<body> and<table>, amongmany others. It provides functionality globally to the document, like how to obtain the page's URL and create new elements in the document.
TheDocument interface describes the common properties and methods for any kind of document. Depending on the document's type (e.g.,HTML,XML, SVG, …), a larger API is available: HTML documents, served with the"text/html" content type, also implement theHTMLDocument interface, whereas XML and SVG documents implement theXMLDocument interface.
In this article
Constructor
Document()Creates a new
Documentobject.
Instance properties
This interface also inherits from theNode andEventTarget interfaces.
Document.activeElementRead onlyReturns the
Elementthat currently has focus.Document.activeViewTransitionRead onlyExperimentalReturns a
ViewTransitioninstance representing theview transition currently active on the document, ornullif there is no active view transition.Document.adoptedStyleSheetsAdd an array of constructed stylesheets to be used by the document.These stylesheets may also be shared with shadow DOM subtrees of the same document.
Document.bodyReturns the
<body>or<frameset>node of the current document.Document.characterSetRead onlyReturns the character set being used by the document.
Document.childElementCountRead onlyReturns the number of child elements of the current document.
Document.childrenRead onlyReturns the child elements of the current document.
Document.compatModeRead onlyIndicates whether the document is rendered inquirks orstrict mode.
Document.contentTypeRead onlyReturns the Content-Type from the MIME Header of the current document.
Document.currentScriptRead onlyReturns the
<script>element whose script is currently being processed andisn't a JavaScript module.Document.doctypeRead onlyReturns the Document Type Definition (DTD) of the current document.
Document.documentElementRead onlyReturns the
Elementthat is a direct child of the document. For HTML documents, this is normally theHTMLHtmlElementobject representing the document's<html>element.Document.documentURIRead onlyReturns the document location as a string.
Document.embedsRead onlyReturns an
HTMLCollectionof the embedded<embed>elements in the document.Document.featurePolicyExperimentalRead onlyReturns the
FeaturePolicyinterface with the feature policies applied to the document.Document.firstElementChildRead onlyReturns the first child element of the current document.
Document.fontsReturns the
FontFaceSetinterface of the current document.Document.formsRead onlyReturns an
HTMLCollectionof the<form>elements in the document.Document.fragmentDirectiveRead onlyReturns the
FragmentDirectivefor the current document.Document.fullscreenElementRead onlyThe element that's currently in full screen mode for this document.
Document.headRead onlyReturns the
<head>element of the current document.Document.hiddenRead onlyReturns a Boolean value indicating if the page is considered hidden or not.
Document.imagesRead onlyReturns an
HTMLCollectionof the images in the document.Document.implementationRead onlyReturns the DOM implementation associated with the current document.
Document.lastElementChildRead onlyReturns the last child element of the current document.
Document.linksRead onlyReturns an
HTMLCollectionof the hyperlinks in the document.Document.pictureInPictureElementRead onlyReturns the
Elementcurrently being presented in picture-in-picture mode in this document.Document.pictureInPictureEnabledRead onlyReturns true if the picture-in-picture feature is enabled.
Document.pluginsRead onlyReturns an
HTMLCollectionof the available plugins.Document.pointerLockElementRead onlyReturns 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.prerenderingRead onlyExperimentalReturns a boolean that indicates whether the document is currently in the process of prerendering, as initiated via theSpeculation Rules API.
Document.scriptsRead onlyReturns an
HTMLCollectionof the<script>elements in the document.Document.scrollingElementRead onlyReturns a reference to the
Elementthat scrolls the document.Document.styleSheetsRead onlyReturns a
StyleSheetListofCSSStyleSheetobjects for stylesheets explicitly linked into, or embedded in a document.Document.timelineRead onlyReturns timeline as a special instance of
DocumentTimelinethat is automatically created on page load.Document.visibilityStateRead onlyReturns a
stringdenoting the visibility state of the document. Possible values arevisible,hidden, andunloaded.
Extensions for HTMLDocument
TheDocument interface for HTML documents inherits from theHTMLDocument interface or is extended for such documents.
Document.cookieReturns a semicolon-separated list of the cookies for that document or sets a single cookie.
Document.defaultViewRead onlyReturns a reference to the window object.
Document.designModeGets/sets the ability to edit the whole document.
Document.dirGets/sets directionality (rtl/ltr) of the document.
Document.fullscreenEnabledRead onlyIndicates whether fullscreen mode is available.
Document.lastModifiedRead onlyReturns the date on which the document was last modified.
Document.locationRead onlyReturns the URI of the current document.
Document.readyStateRead onlyReturns loading status of the document.
Document.referrerRead onlyReturns the URI of the page that linked to this page.
Document.titleSets or gets the title of the current document.
Document.URLRead onlyReturns the document location as a string.
- Named properties
Some elements in the document are also exposed as properties:
- For each
<embed>,<form>,<iframe>,<img>, and<object>element, itsname(if non-empty) is exposed.For example, if the document contains<form name="my_form">, thendocument["my_form"](and its equivalentdocument.my_form) returns a reference to that element. - For each
<object>element, itsid(if non-empty) is exposed. - For each
<img>element with non-emptyname, itsid(if non-empty) is exposed.
If a property corresponds to a single element, that element is directly returned. If that single element is an iframe, then its
contentWindowis returned instead. If the property corresponds to multiple elements, then anHTMLCollectionis returned containing all of them.- For each
Deprecated properties
Document.alinkColorDeprecatedReturns or sets the color of active links in the document body.
Document.allDeprecatedProvides access to all elements in the document — it returns an
HTMLAllCollectionrooted at the document node. This is a legacy, non-standard property and should not be used.Document.anchorsDeprecatedRead onlyReturns a list of all of the anchors in the document.
Document.appletsDeprecatedRead onlyReturns an empty
HTMLCollection. Legacy property that used to return the list of applets within a document.Document.bgColorDeprecatedGets/sets the background color of the current document.
Document.charsetDeprecatedRead onlyAlias of
Document.characterSet. Use this property instead.Document.domainDeprecatedGets/sets the domain of the current document.
Document.fgColorDeprecatedGets/sets the foreground color, or text color, of the current document.
Document.fullscreenDeprecatedReturns
truewhen the document is infullscreen mode.Document.inputEncodingDeprecatedRead onlyAlias of
Document.characterSet. Use this property instead.Document.lastStyleSheetSetDeprecatedRead onlyNon-standardReturns 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.linkColorDeprecatedGets/sets the color of hyperlinks in the document.
Document.preferredStyleSheetSetDeprecatedRead onlyNon-standardReturns the preferred style sheet set as specified by the page author.
Document.rootElementDeprecatedLike
Document.documentElement, but only for<svg>root elements. Use this property instead.Document.selectedStyleSheetSetDeprecatedNon-standardReturns which style sheet set is currently in use.
Document.styleSheetSetsDeprecatedRead onlyNon-standardReturns a list of the style sheet sets available on the document.
Document.vlinkColorDeprecatedGets/sets the color of visited hyperlinks.
Document.xmlEncodingDeprecatedReturns the encoding as determined by the XML declaration.
Document.xmlStandaloneDeprecatedReturns
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.xmlVersionDeprecatedReturns the version number as specified in the XML declaration or
"1.0"if the declaration is absent.
Instance methods
This interface also inherits from theNode andEventTarget interfaces.
Document.adoptNode()Adopt node from an external document.
Document.append()Inserts a set of
Nodeobjects or strings after the last child of the document.Document.ariaNotify()ExperimentalNon-standardSpecifies that a given string of text should be announced by a screen reader.
Document.browsingTopics()ExperimentalNon-standardReturns a promise that fulfills with an array of objects representing the top topics for the user, one from each of the last three epochs. By default, the method also causes the browser to record the current page visit as observed by the caller, so the page's hostname can later be used in topics calculation. See theTopics API for more details.
Document.captureEvents()DeprecatedDocument.caretPositionFromPoint()Returns a
CaretPositionobject containing the DOM node containing the caret, and caret's character offset within that node.Document.caretRangeFromPoint()Non-standardGets a
Rangeobject for the document fragment under the specified coordinates.Document.createAttribute()Creates a new
Attrobject and returns it.Document.createAttributeNS()Creates a new attribute node in a given namespace and returns it.
Document.createCDATASection()Creates a new CDATA node and returns it.
Document.createComment()Creates a new comment node and returns it.
Document.createDocumentFragment()Creates a new document fragment.
Document.createElement()Creates a new element with the given tag name.
Document.createElementNS()Creates a new element with the given tag name and namespace URI.
Document.createEvent()DeprecatedCreates an event object.
Document.createNodeIterator()Creates a
NodeIteratorobject.Document.createProcessingInstruction()Creates a new
ProcessingInstructionobject.Document.createRange()Creates a
Rangeobject.Document.createTextNode()Creates a text node.
Document.createTouch()DeprecatedNon-standardCreates a
Touchobject.Document.createTouchList()DeprecatedNon-standardCreates a
TouchListobject.Document.createTreeWalker()Creates a
TreeWalkerobject.Document.elementFromPoint()Returns the topmost element at the specified coordinates.
Document.elementsFromPoint()Returns an array of all elements at the specified coordinates.
Document.enableStyleSheetsForSet()DeprecatedNon-standardEnables the style sheets for the specified style sheet set.
Document.exitFullscreen()Stops document's fullscreen element from being displayed fullscreen.
Document.exitPictureInPicture()Remove the video from the floating picture-in-picture window back to its original container.
Document.exitPointerLock()Release the pointer lock.
Document.getAnimations()Returns an array of all
Animationobjects currently in effect, whose target elements are descendants of thedocument.Document.getBoxQuads()ExperimentalReturns a list of
DOMQuadobjects representing the CSS fragments of the node.Document.getElementById()Returns an object reference to the identified element.
Document.getElementsByClassName()Returns a list of elements with the given class name.
Document.getElementsByTagName()Returns a list of elements with the given tag name.
Document.getElementsByTagNameNS()Returns a list of elements with the given tag name and namespace.
Document.getSelection()Returns a
Selectionobject representing the range of text selected by the user, or the current position of the caret.Document.hasStorageAccess()Returns a
Promisethat resolves with a boolean value indicating whether the document has access to unpartitioned cookies.Document.hasUnpartitionedCookieAccess()New name for
Document.hasStorageAccess().Document.importNode()Returns a clone of a node from an external document.
Document.moveBefore()Moves a given
Nodeinside theDocumentDOM node as a direct child, before a given reference node, without removing and then inserting the node.Document.mozSetImageElement()Non-standardAllows you to change the element being used as the background image for a specified element ID.
Document.prepend()Inserts a set of
Nodeobjects or strings before the first child of the document.Document.querySelector()Returns the first Element node within the document, in document order, that matches the specified selectors.
Document.querySelectorAll()Returns a list of all the Element nodes within the document that match the specified selectors.
Document.releaseCapture()Non-standardReleases the current mouse capture if it's on an element in this document.
Document.releaseEvents()DeprecatedDocument.replaceChildren()Replaces the existing children of a document with a specified new set of children.
Document.requestStorageAccess()Allows a document loaded in a third-party context (i.e., embedded in an
<iframe>) to request access to unpartitioned cookies, in cases where user agents by default block access to unpartitioned cookies by sites loaded in a third-party context to improve privacy.Document.requestStorageAccessFor()ExperimentalAllows top-level sites to request third-party cookie access on behalf of embedded content originating from another site in the samerelated website set.
Document.startViewTransition()Starts a newview transition and returns a
ViewTransitionobject to represent it.
TheDocument interface is extended with theXPathEvaluator interface:
Document.createExpression()Compiles an
XPathExpressionwhich can then be used for (repeated) evaluations.Document.createNSResolver()DeprecatedReturns the input node as-is.
Document.evaluate()Evaluates an XPath expression.
Extension for HTML documents
TheDocument interface for HTML documents inherit from theHTMLDocument interface or is extended for such documents:
Document.clear()DeprecatedThis method does nothing.
Document.close()Closes a document stream for writing.
Document.execCommand()DeprecatedOn an editable document, executes a formatting command.
Document.getElementsByName()Returns a list of elements with the given name.
Document.hasFocus()Returns
trueif the focus is currently located anywhere inside the specified document.Document.open()Opens a document stream for writing.
Document.queryCommandEnabled()DeprecatedNon-standardReturns true if the formatting command can be executed on the current range.
Document.queryCommandIndeterm()DeprecatedReturns true if the formatting command is in an indeterminate state on the current range.
Document.queryCommandState()DeprecatedNon-standardReturns true if the formatting command has been executed on the current range.
Document.queryCommandSupported()DeprecatedNon-standardReturns true if the formatting command is supported on the current range.
Document.queryCommandValue()DeprecatedReturns the current value of the current range for a formatting command.
Document.write()DeprecatedWrites text in a document.
Document.writeln()DeprecatedWrites a line of text in a document.
Static methods
This interface also inherits from theNode andEventTarget interfaces.
Document.parseHTML()ExperimentalCreates a new
Documentobject from a string of HTML in an XSS-safe manner with sanitization.Document.parseHTMLUnsafe()Creates a new
Documentobject from a string of HTML without performing sanitization.The string may contain declarative shadow roots.
Events
Listen to these events usingaddEventListener() or by assigning an event listener to theoneventname property of this interface. In addition to the events listed below, many events can bubble fromnodes contained in the document tree.
afterscriptexecuteNon-standardDeprecatedFired when a static
<script>element finishes executing its scriptbeforescriptexecuteNon-standardDeprecatedFired when a static
<script>is about to start executing.prerenderingchangeExperimentalFired on a prerendered document when it is activated (i.e., the user views the page).
securitypolicyviolationFired when a content security policy is violated.
visibilitychangeFired when the content of a tab has become visible or has been hidden.
Fullscreen events
fullscreenchangeFired when the
Documenttransitions into or out offullscreen mode.fullscreenerrorFired if an error occurs while attempting to switch into or out offullscreen mode.
Load & unload events
DOMContentLoadedFired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
readystatechangeFired when the
readyStateattribute of a document has changed.
Pointer lock events
pointerlockchangeFired when the pointer is locked/unlocked.
pointerlockerrorFired when locking the pointer failed.
Scroll events
scrollFired when the document view or an element has been scrolled.
scrollendFired when the document view or an element has completed scrolling.
scrollsnapchangeExperimentalFired on the scroll container at the end of a scrolling operation when a new scroll snap target has been selected.
scrollsnapchangingExperimentalFired on the scroll container when the browser determines a new scroll snap target is pending, i.e., it will be selected when the current scroll gesture ends.
Selection events
selectionchangeFired when the current text selection on a document is changed.
Bubbled events
Not all events that bubble can reach theDocument object. Only the following do and can be listened for on theDocument object:
abortauxclickbeforeinputbeforematchbeforetoggleblurcancelcanplaycanplaythroughchangeclickclosecontextlostcontextmenucontextrestoredcopycuechangecutdblclickdragdragenddragenterdragleavedragoverdragstartdropdurationchangeemptiedendederrorfocusformdatainputinvalidkeydownkeypresskeyuploadloadeddataloadedmetadataloadstartmousedownmouseentermouseleavemousemovemouseoutmouseovermouseuppastepauseplayplayingprogressratechangeresetresizescrollscrollendsecuritypolicyviolationseekedseekingselectslotchangestalledsubmitsuspendtimeupdatetogglevolumechangewaitingwheel