Esta página foi traduzida do inglês pela comunidade.Saiba mais e junte-se à comunidade MDN Web Docs.
Document
Baseline Widely available *
This feature is well established and works across many devices and browser versions. It’s been available across browsers since julho de 2015.
* Some parts of this feature may have varying levels of support.
Para cada página carregada no browser, existe um objetoDocument. A interfaceDocument serve como um ponto de entrada para o conteúdo da Página ( a árvore DOM, incluindo elementos como<body> e<table>) e provê funcionalidades globais ao documento (como obter a URL da página e criar novos elementos no documento).
Um objeto document pode ser obtido por meio de várias APIs:
- A mais comum; você trabalha com o script do documento que está rodando o script com o objeto document. (O mesmo document também pode ser referenciado como
window.document.) - O documento de um iframe através da propriedade
contentDocument. - O
responseXMLde um objetoXMLHttpRequest. - O documento ao qual um determinado node ou elemento pertence pode ser recuperado usando a propriedade do node
ownerDocument
Dependendo do tipo do documento (e.g.HTML ouXML), diferentes APIs estarão disponívels no objetoDocument.
Todo objetoDocument implementa a interfaceDocument (e consequentemente as interfacesNode eEventTarget). Portanto, as principais propriedades e métodos documentados nesta página estarão disponíveis para todos os tipos de documents.
- Em navegadores mais atuais, alguns documentos (ex: aqueles que são servidos com o Content-Type
text/html) também implementam a interfaceHTMLDocument. - Em navegadores mais atuais, documentos SVG implementam a interface
SVGDocument.
No futuro, todas essas interfaces irão ser divididas na interfaceDocument.
In this article
Propriedades
Nota:A interfaceDocument também herda das interfacesNode eEventTarget.
Document.allDeprecatedNão padrãoDa acesso a todos os elementos do documento.È uma interface legada não padrão, voce deve usar o método
Document.getElementById()como alternativa.Document.asyncDeprecatedUsado como
document.loadque indica uma requisição asyncroma.Document.characterSetExperimentalRetorna a codificação de caracteres que está sendo usado pelo documento.
Document.compatModeExperimentalindica se o documento é renderizado no modo Quirks ou Strict.
Document.contentTypeExperimentalRetorna o tipo de conteúdo do cabeçalho MIME do documento atual.
Document.doctypeRetorna o nome do tipo de conteudo do documento HTML.
Document.documentElementReturns the Element that is a direct child of the document. For HTML documents, this is normally the HTML element.
Document.documentURIReturns the document URL.
Document.domConfigDeprecatedShould return a
DOMConfigurationobject.Document.implementationReturns the DOM implementation associated with the current document.
Document.inputEncodingDeprecatedReturns the encoding used when the document was parsed.
Document.lastStyleSheetSetReturns 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.mozSyntheticDocumentNão padrãotrueif this document is synthetic, such as a standalone image, video, audio file, or the like.Document.mozFullScreenNão padrãotruewhen the document is infull-screen mode.Document.mozFullScreenElementNão padrãoThe element that's currently in full screen mode for this document.
Document.mozFullScreenEnabledNão padrãotrueif callingelement.mozRequestFullscreen()would succeed in the curent document.Document.pointerLockElementExperimentalReturns 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.preferredStyleSheetSetReturns the preferred style sheet set as specified by the page author.
Document.selectedStyleSheetSetReturns which style sheet set is currently in use.
Document.styleSheetsReturns a list of the style sheet objects on the current document.
Document.styleSheetSetsReturns a list of the style sheet sets available on the document.
Document.xmlEncodingDeprecatedReturns the encoding as determined by the XML declaration.
Document.xmlStandaloneReturns
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.xmlVersionReturns the version number as specified in the XML declaration or
"1.0"if the declaration is absent.
TheDocument interface is extended with theParentNode interface:
Extension for HTML documents
TheDocument interface for HTML documents inherit from theHTMLDocument interface or, since HTML5, is extended for such documents:
Document.activeElementReturns the currently focused element.
Document.alinkColorDeprecatedReturns or sets the color of active links in the document body.
Document.anchorsReturns a list of all of the anchors in the document.
Document.appletsDeprecatedReturns an ordered list of the applets within a document.
Document.bgColorDeprecatedGets/sets the background color of the current document.
Document.bodyReturns the
<body>element of the current document.Document.cookieReturns a semicolon-separated list of the cookies for that document or sets a single cookie.
Document.defaultViewReturns 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.domainReturns the domain of the current document.
Document.embedsReturns a list of the embedded
<embed>elements within the current document.Document.fgColorDeprecatedGets/sets the foreground color, or text color, of the current document.
Document.formsReturns a list of the
<form>elements within the current document.Document.headReturns the
<head>element of the current document.Document.heightNão padrãoGets/sets the height of the current document.
Document.imagesReturns a list of the images in the current document.
Document.lastModifiedReturns the date on which the document was last modified.
Document.linkColorDeprecatedGets/sets the color of hyperlinks in the document.
Document.linksReturns a list of all the hyperlinks in the document.
Document.locationReturns the URI of the current document.
Document.pluginsReturns a list of the available plugins.
Document.readyStateReturns loading status of the document.
Document.referrerReturns the URI of the page that linked to this page.
Document.scriptsReturns all the
<script>elements on the document.Document.titleReturns the title of the current document.
Document.URLReturns a string containing the URL of the current document.
Document.vlinkColorDeprecatedGets/sets the color of visited hyperlinks.
Document.widthNão padrãoReturns the width of the current document.
Event handlers
Document.onpointerlockchangeExperimentalReturns the event handling code for the
pointerlockchangeevent.Document.onpointerlockerrorExperimentalReturns the event handling code for the
pointerlockerrorevent.Document.onreadystatechangeReturns the event handling code for the
readystatechangeevent.
Methods
Nota:TheDocument interface also inherits from theNode andEventTarget interfaces.
Document.adoptNode(Node node)Adopt node from an external document.
Document.captureEvents(String eventName)DeprecatedDocument.caretPositionFromPoint(Number x, Number y)Gets a
CaretPositionbased on two 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 element visible at the specified coordinates.
Document.enableStyleSheetsForSet(String name)Enables the style sheets for the specified style sheet set.
Document.exitPointerLock()ExperimentalRelease 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.mozSetImageElementNão padrãoAllows you to change the element being used as the background image for a specified element ID.
Document.normalizeDocument()Replaces entities, normalizes text nodes, etc.
Document.releaseCapture()Não padrãoReleases the current mouse capture if it's on an element in this document.
Document.releaseEventsNão padrãoDeprecateddocument.routeEventNão padrão
TheDocument interface is extended with theParentNode 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.
TheDocument interface is extended with theXPathEvaluator 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
TheDocument interface for HTML documents inherit from theHTMLDocument interface or, since HTML5, is extended for such documents:
Document.clear()Não padrãoDeprecatedIn 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 formatting command.
Document.registerElement(String tagname[, Object options])Registers a new custom element in the browser and returns a constructor for the new element.
Document.write(String text)Writes text in a document.
Document.writeln(String text)Writes a line of text in a document.
Specifications
Compatibilidade com navegadores
>Firefox notes
Mozilla defines a set of non-standard properties made only for XUL content:
document.currentScriptReturns 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.popupNodeReturns the node upon which a popup was invoked.
document.tooltipNodeReturns the node which is the target of the current tooltip.
Mozilla also define some non-standard methods:
Document.execCommandShowHelpThis method never did anything and always threw an exception, so it was removed in Gecko 14.0.
Document.getBoxObjectForUse the
Element.getBoundingClientRect()method instead.Document.loadOverlayLoads aXUL overlay dynamically. This only works in XUL documents.
document.queryCommandTextThis method never did anything but throw an exception, and was removed in Gecko 14.0.
Internet Explorer notes
Microsoft defines some non-standard properties:
document.fileSize*Não padrãoReturns size in bytes of the document. Starting with Internet Explorer 11, that property is no longer supported. SeeMSDN.Internet Explorer does not support all methods from the
Nodeinterface in theDocumentinterfacedocument.containsAs a work-around,
document.body.contains()can be used.