DOM 是 Document Object Model(文档对象模型)的缩写。通过 HTML DOM, JavaScript 能够访问 HTML 文档中的每个元素。本文可以保存后用到时再来查看。

学习HTML DOM作为基础,以后学习和理解JavaScript会非常容易。

DOM 定义了访问 HTML 和 XML 文档的标准:

“W3C 文档对象模型 (DOM) 是中立于平台和语言的接口,它允许程序和脚本动态地访问和更新文档的内容、结构和样式。” W3C DOM 标准被分为 3 个不同的部分:

  • 核心 DOM - 针对任何结构化文档的标准模型
  • XML DOM - 针对 XML 文档的标准模型
  • HTML DOM - 针对 HTML 文档的标准模型

HTML DOM 定义了所有 HTML 元素对象属性,以及访问它们的方法

HTML DOM 是关于如何获取、修改、添加或删除 HTML 元素的标准。

节点节点树概念

在 HTML DOM 中,所有事物都是节点。DOM 是被视为节点树的 HTML。

节点与节点之间的关系可以是: 父子关系(上下层)兄弟关系(同层)

最顶层的节点叫做根节点(root),他没有父节点和兄弟节点。

节点和节点树说的是对HTML文档的数据结构的抽象存储结构

而具体的对象节点存储结构基础上实现的操作方法封装。

属性Attributes对象

HTML DOM中, 属性对象是属于一个HTML元素,包含了属性namevalue属性和两个状态判断属性isIdspecified

属性的访问和处理函数有哪些呢?对于属性的操作是使用NamedNodeMap对象来完成的。下面了解下NNM吧。

NamedNodeMap(NNM)对象

NNM 对象表示一个元素属性节点的无序集合。在NNM中的节点可以通过nameindex(数字序号)访问。

NNM对象的属性和方法如下:

Property / MethodDescription
attr.isId判断属性是否是Id,True表示是,False表示不是,目前浏览器都删除对此属性的支持
attr.name查看属性名称
attr.value设置或者查看属性值
attr.specified查明是否已指定属性,True表示已指定或已创建但尚未附加到元素,False表示未指定
nodemap.getNamedItem()获取指定的属性节点
nodemap.item()返回NamedNodeMap上指定序号的属性节点
nodemap.length返回NamedNodeMap上属性的节点数量
nodemap.removeNamedItem()删除Removes a specified attribute node
nodemap.setNamedItem()Sets the specified attribute node (by name)

示例:

HTML
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<html>
        <body>
                <p id="intro" class="test" >Hello World!</p>
                <script>
                        //var txt=document.getElementById("intro").innerHTML;
                        var p=document.getElementById("intro");
                        var txt=p.attributes.getNamedItem('id').value
                        document.write(txt);
                        //获取<p>元素的第一个属性的名称:
                        var x = document.getElementById("intro").attributes.item(0).nodeName;
                        document.write('<br>' + x)
                </script>
        </body>
</html>

页面执行结果:

Hello World!
intro
id

HTMLDOM的Document对象

当HTML文档被加载到Web浏览器时 就在浏览器中变成了一个document对象, document对象就是这个HTML文档节点树的根节点。 操作document对象就是在操作这个节点树。

document对象的属性和方法

Property / MethodDescription
activeElementReturns the currently focused element in the document
addEventListener()Attaches an event handler to the document
adoptNode()Adopts a node from another document
anchorsReturns a collection of all <a> elements in the document that have a name attribute
appletsReturns a collection of all <applet> elements in the document
baseURIReturns the absolute base URI of a document
bodySets or returns the document’s body (the <body> element)
close()Closes the output stream previously opened with document.open()
cookieReturns all name/value pairs of cookies in the document
charsetDeprecated. Use characterSet instead. Returns the character encoding for the document
characterSetReturns the character encoding for the document
createAttribute()Creates an attribute node
createComment()Creates a Comment node with the specified text
createDocumentFragment()Creates an empty DocumentFragment node
createElement()Creates an Element node
createEvent()Creates a new event
createTextNode()Creates a Text node
defaultViewReturns the window object associated with a document, or null if none is available.
designModeControls whether the entire document should be editable or not.
doctypeReturns the Document Type Declaration associated with the document
documentElementReturns the Document Element of the document (the <html> element)
documentModeReturns the mode used by the browser to render the document
documentURISets or returns the location of the document
domainReturns the domain name of the server that loaded the document
domConfigObsolete. Returns the DOM configuration of the document
embedsReturns a collection of all <embed> elements the document
execCommand()Invokes the specified clipboard operation on the element currently having focus.
formsReturns a collection of all <form> elements in the document
fullscreenElementReturns the current element that is displayed in fullscreen mode
fullscreenEnabled()Returns a Boolean value indicating whether the document can be viewed in fullscreen mode
getElementById()Returns the element that has the ID attribute with the specified value
getElementsByClassName()Returns a HTMLCollection containing all elements with the specified class name
getElementsByName()Returns a HTMLCollection containing all elements with a specified name
getElementsByTagName()Returns a HTMLCollection containing all elements with the specified tag name
hasFocus()Returns a Boolean value indicating whether the document has focus
headReturns the <head> element of the document
imagesReturns a collection of all <img> elements in the document
implementationReturns the DOMImplementation object that handles this document
importNode()Imports a node from another document
inputEncodingReturns the encoding, character set, used for the document
lastModifiedReturns the date and time the document was last modified
linksReturns a collection of all <a> and <area> elements in the document that have a href attribute
normalize()Removes empty Text nodes, and joins adjacent nodes
normalizeDocument()Removes empty Text nodes, and joins adjacent nodes
open()Opens an HTML output stream to collect output from document.write()
querySelector()Returns the first element that matches a specified CSS selector(s) in the document
querySelectorAll()Returns a static NodeList containing all elements that matches a specified CSS selector(s) in the document
readyStateReturns the (loading) status of the document
referrerReturns the URL of the document that loaded the current document
removeEventListener()Removes an event handler from the document (that has been attached with the addEventListener() method)
renameNode()Renames the specified node
scriptsReturns a collection of <script> elements in the document
strictErrorCheckingSets or returns whether error-checking is enforced or not
titleSets or returns the title of the document
URLReturns the full URL of the HTML document
write()Writes HTML expressions or JavaScript code to a document
writeln()Same as write(), but adds a newline character after each statement

Element元素对象

Element对象表示的是HTML页面的元素,例如 p,input,DIV等等其他任何HTML元素。

Element元素对象的属性和方法

下面属性和方法适用于所有的HTML元素

Property / MethodDescription
accessKeySets or returns the accesskey attribute of an element
addEventListener()Attaches an event handler to the specified element
appendChild()Adds a new child node, to an element, as the last child node
attributesReturns a NamedNodeMap of an element’s attributes
blur()Removes focus from an element
childElementCountReturns the number of child elements an element has
childNodesReturns a collection of an element’s child nodes (including text and comment nodes)
childrenReturns a collection of an element’s child element (excluding text and comment nodes)
classListReturns the class name(s) of an element
classNameSets or returns the value of the class attribute of an element
click()Simulates a mouse-click on an element
clientHeightReturns the height of an element, including padding
clientLeftReturns the width of the left border of an element
clientTopReturns the width of the top border of an element
clientWidthReturns the width of an element, including padding
cloneNode()Clones an element
compareDocumentPosition()Compares the document position of two elements
contains()Returns true if a node is a descendant of a node, otherwise false
contentEditableSets or returns whether the content of an element is editable or not
dirSets or returns the value of the dir attribute of an element
exitFullscreen()Cancels an element in fullscreen mode
firstChildReturns the first child node of an element
firstElementChildReturns the first child element of an element
focus()Gives focus to an element
getAttribute()Returns the specified attribute value of an element node
getAttributeNode()Returns the specified attribute node
getBoundingClientRect()Returns the size of an element and its position relative to the viewport
getElementsByClassName()Returns a collection of all child elements with the specified class name
getElementsByTagName()Returns a collection of all child elements with the specified tag name
hasAttribute()Returns true if an element has the specified attribute, otherwise false
hasAttributes()Returns true if an element has any attributes, otherwise false
hasChildNodes()Returns true if an element has any child nodes, otherwise false
idSets or returns the value of the id attribute of an element
innerHTMLSets or returns the content of an element
innerTextSets or returns the text content of a node and its descendants
insertAdjacentElement()Inserts a HTML element at the specified position relative to the current element
insertAdjacentHTML()Inserts a HTML formatted text at the specified position relative to the current element
insertAdjacentText()Inserts text into the specified position relative to the current element
insertBefore()Inserts a new child node before a specified, existing, child node
isContentEditableReturns true if the content of an element is editable, otherwise false
isDefaultNamespace()Returns true if a specified namespaceURI is the default, otherwise false
isEqualNode()Checks if two elements are equal
isSameNode()Checks if two elements are the same node
isSupported()Returns true if a specified feature is supported on the element
langSets or returns the value of the lang attribute of an element
lastChildReturns the last child node of an element
lastElementChildReturns the last child element of an element
namespaceURIReturns the namespace URI of an element
nextSiblingReturns the next node at the same node tree level
nextElementSiblingReturns the next element at the same node tree level
nodeNameReturns the name of a node
nodeTypeReturns the node type of a node
nodeValueSets or returns the value of a node
normalize()Joins adjacent text nodes and removes empty text nodes in an element
offsetHeightReturns the height of an element, including padding, border and scrollbar
offsetWidthReturns the width of an element, including padding, border and scrollbar
offsetLeftReturns the horizontal offset position of an element
offsetParentReturns the offset container of an element
offsetTopReturns the vertical offset position of an element
outerHTMLSets or returns the content of an element (including the start tag and the end tag)
outerTextSets or returns the outer text content of a node and its descendants
ownerDocumentReturns the root element (document object) for an element
parentNodeReturns the parent node of an element
parentElementReturns the parent element node of an element
previousSiblingReturns the previous node at the same node tree level
previousElementSiblingReturns the previous element at the same node tree level
querySelector()Returns the first child element that matches a specified CSS selector(s) of an element
querySelectorAll()Returns all child elements that matches a specified CSS selector(s) of an element
remove()Removes the element from the DOM
removeAttribute()Removes a specified attribute from an element
removeAttributeNode()Removes a specified attribute node, and returns the removed node
removeChild()Removes a child node from an element
removeEventListener()Removes an event handler that has been attached with the addEventListener() method
replaceChild()Replaces a child node in an element
requestFullscreen()Shows an element in fullscreen mode
scrollHeightReturns the entire height of an element, including padding
scrollIntoView()Scrolls the specified element into the visible area of the browser window
scrollLeftSets or returns the number of pixels an element’s content is scrolled horizontally
scrollTopSets or returns the number of pixels an element’s content is scrolled vertically
scrollWidthReturns the entire width of an element, including padding
setAttribute()Sets or changes the specified attribute, to the specified value
setAttributeNode()Sets or changes the specified attribute node
styleSets or returns the value of the style attribute of an element
tabIndexSets or returns the value of the tabindex attribute of an element
tagNameReturns the tag name of an element
textContentSets or returns the textual content of a node and its descendants
titleSets or returns the value of the title attribute of an element
toString()Converts an element to a string

HTMLDOM的Events事件对象

HTML DOM事件允许 JavaScript 在HTML文档中的元素上注册不同的事件处理程序。 事件通常与功能结合使用,并且在事件发生之前(例如,用户单击按钮时)不会执行该功能。

EventDescriptionBelongs To
abortThe event occurs when the loading of a media is abortedUiEvent, Event
afterprintThe event occurs when a page has started printing, or if the print dialogue box has been closedEvent
animationendThe event occurs when a CSS animation has completedAnimationEvent
animationiterationThe event occurs when a CSS animation is repeatedAnimationEvent
animationstartThe event occurs when a CSS animation has startedAnimationEvent
beforeprintThe event occurs when a page is about to be printedEvent
beforeunloadThe event occurs before the document is about to be unloadedUiEvent, Event
blurThe event occurs when an element loses focusFocusEvent
canplayThe event occurs when the browser can start playing the media (when it has buffered enough to begin)Event
canplaythroughThe event occurs when the browser can play through the media without stopping for bufferingEvent
changeThe event occurs when the content of a form element, the selection, or the checked state have changed (for <input>, <select>, and <textarea>)Event
clickThe event occurs when the user clicks on an elementMouseEvent
contextmenuThe event occurs when the user right-clicks on an element to open a context menuMouseEvent
copyThe event occurs when the user copies the content of an elementClipboardEvent
cutThe event occurs when the user cuts the content of an elementClipboardEvent
dblclickThe event occurs when the user double-clicks on an elementMouseEvent
dragThe event occurs when an element is being draggedDragEvent
dragendThe event occurs when the user has finished dragging an elementDragEvent
dragenterThe event occurs when the dragged element enters the drop targetDragEvent
dragleaveThe event occurs when the dragged element leaves the drop targetDragEvent
dragoverThe event occurs when the dragged element is over the drop targetDragEvent
dragstartThe event occurs when the user starts to drag an elementDragEvent
dropThe event occurs when the dragged element is dropped on the drop targetDragEvent
durationchangeThe event occurs when the duration of the media is changedEvent
endedThe event occurs when the media has reach the end (useful for messages like “thanks for listening”)Event
errorThe event occurs when an error occurs while loading an external fileProgressEvent, UiEvent, Event
focusThe event occurs when an element gets focusFocusEvent
focusinThe event occurs when an element is about to get focusFocusEvent
focusoutThe event occurs when an element is about to lose focusFocusEvent
fullscreenchangeThe event occurs when an element is displayed in fullscreen modeEvent
fullscreenerrorThe event occurs when an element can not be displayed in fullscreen modeEvent
hashchangeThe event occurs when there has been changes to the anchor part of a URLHashChangeEvent
inputThe event occurs when an element gets user inputInputEvent, Event
invalidThe event occurs when an element is invalidEvent
keydownThe event occurs when the user is pressing a keyKeyboardEvent
keypressThe event occurs when the user presses a keyKeyboardEvent
keyupThe event occurs when the user releases a keyKeyboardEvent
loadThe event occurs when an object has loadedUiEvent, Event
loadeddataThe event occurs when media data is loadedEvent
loadedmetadataThe event occurs when meta data (like dimensions and duration) are loadedEvent
loadstartThe event occurs when the browser starts looking for the specified mediaProgressEvent
messageThe event occurs when a message is received through the event sourceEvent
mousedownThe event occurs when the user presses a mouse button over an elementMouseEvent
mouseenterThe event occurs when the pointer is moved onto an elementMouseEvent
mouseleaveThe event occurs when the pointer is moved out of an elementMouseEvent
mousemoveThe event occurs when the pointer is moving while it is over an elementMouseEvent
mouseoverThe event occurs when the pointer is moved onto an element, or onto one of its childrenMouseEvent
mouseoutThe event occurs when a user moves the mouse pointer out of an element, or out of one of its childrenMouseEvent
mouseupThe event occurs when a user releases a mouse button over an elementMouseEvent
mousewheelDeprecated. Use the wheel event insteadWheelEvent
offlineThe event occurs when the browser starts to work offlineEvent
onlineThe event occurs when the browser starts to work onlineEvent
openThe event occurs when a connection with the event source is openedEvent
pagehideThe event occurs when the user navigates away from a webpagePageTransitionEvent
pageshowThe event occurs when the user navigates to a webpagePageTransitionEvent
pasteThe event occurs when the user pastes some content in an elementClipboardEvent
pauseThe event occurs when the media is paused either by the user or programmaticallyEvent
playThe event occurs when the media has been started or is no longer pausedEvent
playingThe event occurs when the media is playing after having been paused or stopped for bufferingEvent
popstateThe event occurs when the window’s history changesPopStateEvent
progressThe event occurs when the browser is in the process of getting the media data (downloading the media)Event
ratechangeThe event occurs when the playing speed of the media is changedEvent
resizeThe event occurs when the document view is resizedUiEvent, Event
resetThe event occurs when a form is resetEvent
scrollThe event occurs when an element’s scrollbar is being scrolledUiEvent, Event
searchThe event occurs when the user writes something in a search field (for <input=“search”>)Event
seekedThe event occurs when the user is finished moving/skipping to a new position in the mediaEvent
seekingThe event occurs when the user starts moving/skipping to a new position in the mediaEvent
selectThe event occurs after the user selects some text (for <input> and <textarea>)UiEvent, Event
showThe event occurs when a <menu> element is shown as a context menuEvent
stalledThe event occurs when the browser is trying to get media data, but data is not availableEvent
storageThe event occurs when a Web Storage area is updatedStorageEvent
submitThe event occurs when a form is submittedEvent
suspendThe event occurs when the browser is intentionally not getting media dataEvent
timeupdateThe event occurs when the playing position has changed (like when the user fast forwards to a different point in the media)Event
toggleThe event occurs when the user opens or closes the <details> elementEvent
touchcancelThe event occurs when the touch is interruptedTouchEvent
touchendThe event occurs when a finger is removed from a touch screenTouchEvent
touchmoveThe event occurs when a finger is dragged across the screenTouchEvent
touchstartThe event occurs when a finger is placed on a touch screenTouchEvent
transitionendThe event occurs when a CSS transition has completedTransitionEvent
unloadThe event occurs once a page has unloaded (for <body>)UiEvent, Event
volumechangeThe event occurs when the volume of the media has changed (includes setting the volume to “mute”)Event
waitingThe event occurs when the media has paused but is expected to resume (like when the media pauses to buffer more data)Event
wheelThe event occurs when the mouse wheel rolls up or down over an elementWheelEvent

HTMLDOM的Event事件对象的属性和方法

Property/MethodDescriptionBelongs To
altKeyReturns whether the “ALT” key was pressed when the mouse event was triggeredMouseEvent
altKeyReturns whether the “ALT” key was pressed when the key event was triggeredKeyboardEvent, TouchEvent
animationNameReturns the name of the animationAnimationEvent
bubblesReturns whether or not a specific event is a bubbling eventEvent
buttonReturns which mouse button was pressed when the mouse event was triggeredMouseEvent
buttonsReturns which mouse buttons were pressed when the mouse event was triggeredMouseEvent
cancelableReturns whether or not an event can have its default action preventedEvent
charCodeReturns the Unicode character code of the key that triggered the onkeypress eventKeyboardEvent
changeTouchesReturns a list of all the touch objects whose state changed between the previous touch and this touchTouchEvent
clientXReturns the horizontal coordinate of the mouse pointer, relative to the current window, when the mouse event was triggeredMouseEvent, TouchEvent
clientYReturns the vertical coordinate of the mouse pointer, relative to the current window, when the mouse event was triggeredMouseEvent, TouchEvent
clipboardDataReturns an object containing the data affected by the clipboard operationClipboardData
codeReturns the code of the key that triggered the eventKeyboardEvent
composedReturns whether the event is composed or notEvent
createEvent()Creates a new eventEvent
ctrlKeyReturns whether the “CTRL” key was pressed when the mouse event was triggeredMouseEvent
ctrlKeyReturns whether the “CTRL” key was pressed when the key event was triggeredKeyboardEvent, TouchEvent
currentTargetReturns the element whose event listeners triggered the eventEvent
dataReturns the inserted charactersInputEvent
dataTransferReturns an object containing the data being dragged/dropped, or inserted/deletedDragEvent, InputEvent
defaultPreventedReturns whether or not the preventDefault() method was called for the eventEvent
deltaXReturns the horizontal scroll amount of a mouse wheel (x-axis)WheelEvent
deltaYReturns the vertical scroll amount of a mouse wheel (y-axis)WheelEvent
deltaZReturns the scroll amount of a mouse wheel for the z-axisWheelEvent
deltaModeReturns a number that represents the unit of measurements for delta values (pixels, lines or pages)WheelEvent
detailReturns a number that indicates how many times the mouse was clickedUiEvent
elapsedTimeReturns the number of seconds an animation has been runningAnimationEvent
elapsedTimeReturns the number of seconds a transition has been running
eventPhaseReturns which phase of the event flow is currently being evaluatedEvent
getTargetRanges()Returns an array containing target ranges that will be affected by the insertion/deletionInputEvent
getModifierState()Returns an array containing target ranges that will be affected by the insertion/deletionMouseEvent
inputTypeReturns the type of the change (i.e “inserting” or “deleting”)InputEvent
isComposingReturns whether the state of the event is composing or notInputEvent, KeyboardEvent
isTrustedReturns whether or not an event is trustedEvent
keyReturns the key value of the key represented by the eventKeyboardEvent
keyReturns the key of the changed storage itemStorageEvent
keyCodeReturns the Unicode character code of the key that triggered the onkeypress event, or the Unicode key code of the key that triggered the onkeydown or onkeyup eventKeyboardEvent
locationReturns the location of a key on the keyboard or deviceKeyboardEvent
lengthComputableReturns whether the length of the progress can be computable or notProgressEvent
loadedReturns how much work has been loadedProgressEvent
metaKeyReturns whether the “META” key was pressed when an event was triggeredMouseEvent
metaKeyReturns whether the “meta” key was pressed when the key event was triggeredKeyboardEvent, TouchEvent
MovementXReturns the horizontal coordinate of the mouse pointer relative to the position of the last mousemove eventMouseEvent
MovementYReturns the vertical coordinate of the mouse pointer relative to the position of the last mousemove eventMouseEvent
newValueReturns the new value of the changed storage itemStorageEvent
newURLReturns the URL of the document, after the hash has been changedHasChangeEvent
offsetXReturns the horizontal coordinate of the mouse pointer relative to the position of the edge of the target elementMouseEvent
offsetYReturns the vertical coordinate of the mouse pointer relative to the position of the edge of the target elementMouseEvent
oldValueReturns the old value of the changed storage itemStorageEvent
oldURLReturns the URL of the document, before the hash was changedHasChangeEvent
onemptiedThe event occurs when something bad happens and the media file is suddenly unavailable (like unexpectedly disconnects)
pageXReturns the horizontal coordinate of the mouse pointer, relative to the document, when the mouse event was triggeredMouseEvent
pageYReturns the vertical coordinate of the mouse pointer, relative to the document, when the mouse event was triggeredMouseEvent
persistedReturns whether the webpage was cached by the browserPageTransitionEvent
preventDefault()Cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occurEvent
propertyNameReturns the name of the CSS property associated with the animation or transitionAnimationEvent, TransitionEvent
pseudoElementReturns the name of the pseudo-element of the animation or transitionAnimationEvent, TransitionEvent
regionMouseEvent
relatedTargetReturns the element related to the element that triggered the mouse eventMouseEvent
relatedTargetReturns the element related to the element that triggered the eventFocusEvent
repeatReturns whether a key is being hold down repeatedly, or notKeyboardEvent
screenXReturns the horizontal coordinate of the mouse pointer, relative to the screen, when an event was triggeredMouseEvent
screenYReturns the vertical coordinate of the mouse pointer, relative to the screen, when an event was triggeredMouseEvent
shiftKeyReturns whether the “SHIFT” key was pressed when an event was triggeredMouseEvent
shiftKeyReturns whether the “SHIFT” key was pressed when the key event was triggeredKeyboardEvent, TouchEvent
stateReturns an object containing a copy of the history entriesPopStateEvent
stopImmediatePropagation()Prevents other listeners of the same event from being calledEvent
stopPropagation()Prevents further propagation of an event during event flowEvent
storageAreaReturns an object representing the affected storage objectStorageEvent
targetReturns the element that triggered the eventEvent
targetTouchesReturns a list of all the touch objects that are in contact with the surface and where the touchstart event occured on the same target element as the current target elementTouchEvent
timeStampReturns the time (in milliseconds relative to the epoch) at which the event was createdEvent
totalReturns the total amount of work that will be loadedProgressEvent
touchesReturns a list of all the touch objects that are currently in contact with the surfaceTouchEvent
transitionendThe event occurs when a CSS transition has completedTransitionEvent
typeReturns the name of the eventEvent
urlReturns the URL of the changed item’s documentStorageEvent
whichReturns which mouse button was pressed when the mouse event was triggeredMouseEvent
whichReturns the Unicode character code of the key that triggered the onkeypress event, or the Unicode key code of the key that triggered the onkeydown or onkeyup eventKeyboardEvent
viewReturns a reference to the Window object where the event occurredUiEvent

关于事件对象

当HTML中发生事件时,该事件属于某个事件对象,例如,鼠标单击事件属于MouseEvent对象。 所有事件对象均基于Event事件对象,并继承其所有属性和方法。

基于Event事件对象事件的常见事件对象

这些是最常见的事件对象:

Event ObjectDescription
AnimationEventFor CSS animations
ClipboardEventFor modification of the clipboard
DragEventFor drag and drop interaction
FocusEventFor focus-related events
HashChangeEventFor changes in the anchor part of the URL
InputEventFor user input
KeyboardEventFor keyboard interaction
MouseEventFor mouse interaction
PageTransitionEventFor navigating to, and away from, web pages
PopStateEventFor changes in the history entry
ProgressEventFor the progress of loading external resources
StorageEventFor changes in the window’s storage area.
TouchEventFor touch interaction
TransitionEventFor CSS transitions
UiEventFor user interface interaction
WheelEventFor mousewheel interaction

HTML DOMCollection集合对象

HTMLCollection对象是HTML元素的类似数组的列表。

诸如 getElementsByTagName()之类的方法将返回HTMLCollection

HTML集合的属性和方法

可以在HTMLCollection对象上使用以下属性和方法:

Property / MethodDescription
item()Returns the element at the specified index in an HTMLCollection
lengthReturns the number of elements in an HTMLCollection
namedItem()Returns the element with the specified ID, or name, in an HTMLCollection

示例: 循环遍历HTMLCollection中的每个元素:

JavaScript
1
2
3
4
5
x = document.getElementsByTagName("P");
l = x.length;
for (i = 0; i < l; i++) {
  document.write(x[i].tagName + "<br>");
}

location位置对象

位置对象包含有关当前URL的信息。

location对象是window对象的一部分,可以通过window.location属性进行访问。

注意:没有适用于位置对象的公共标准,但是所有主流浏览器都支持它。

位置对象属性

PropertyDescription
hashSets or returns the anchor part (#) of a URL
hostSets or returns the hostname and port number of a URL
hostnameSets or returns the hostname of a URL
hrefSets or returns the entire URL
originReturns the protocol, hostname and port number of a URL
pathnameSets or returns the path name of a URL
portSets or returns the port number of a URL
protocolSets or returns the protocol of a URL
searchSets or returns the querystring part of a URL

定位对象方法

MethodDescription
assign()Loads a new document
reload()Reloads the current document
replace()Replaces the current document with a new one

导航器对象

导航器对象包含有关浏览器的信息。

注意:没有适用于导航器对象的公共标准,但是所有主要的浏览器都支持它。

导航器对象属性

PropertyDescription
appCodeNameReturns the code name of the browser
appNameReturns the name of the browser
appVersionReturns the version information of the browser
cookieEnabledDetermines whether cookies are enabled in the browser
geolocationReturns a Geolocation object that can be used to locate the user’s position
languageReturns the language of the browser
onLineDetermines whether the browser is online
platformReturns for which platform the browser is compiled
productReturns the engine name of the browser
userAgentReturns the user-agent header sent by the browser to the server

导航器对象方法

MethodDescription
javaEnabled()指定浏览器是否启用了Java支持
taintEnabled()Removed in JavaScript version 1.2. 指定浏览器是否启用了数据污染

屏幕对象

屏幕对象包含有关访客屏幕的信息。

注意:没有适用于屏幕对象的公共标准,但是所有主要的浏览器都支持它。

屏幕对象属性

PropertyDescription
availHeightReturns the height of the screen (excluding the Windows Taskbar)
availWidthReturns the width of the screen (excluding the Windows Taskbar)
colorDepthReturns the bit depth of the color palette for displaying images
heightReturns the total height of the screen
pixelDepthReturns the color resolution (in bits per pixel) of the screen
widthReturns the total width of the screen

HTMLDOM的Style样式对象

Style对象代表单个样式声明。

样式对象属性

“ CSS”列指示该属性在哪个CSS版本中定义(CSS1,CSS2或CSS3)。

PropertyDescriptionCSS
alignContentSets or returns the alignment between the lines inside a flexible container when the items do not use all available space3
alignItemsSets or returns the alignment for items inside a flexible container3
alignSelfSets or returns the alignment for selected items inside a flexible container3
animationA shorthand property for all the animation properties below, except the animationPlayState property3
animationDelaySets or returns when the animation will start3
animationDirectionSets or returns whether or not the animation should play in reverse on alternate cycles3
animationDurationSets or returns how many seconds or milliseconds an animation takes to complete one cycle3
animationFillModeSets or returns what values are applied by the animation outside the time it is executing3
animationIterationCountSets or returns the number of times an animation should be played3
animationNameSets or returns a name for the @keyframes animation3
animationTimingFunctionSets or returns the speed curve of the animation3
animationPlayStateSets or returns whether the animation is running or paused3
backgroundSets or returns all the background properties in one declaration1
backgroundAttachmentSets or returns whether a background-image is fixed or scrolls with the page1
backgroundColorSets or returns the background-color of an element1
backgroundImageSets or returns the background-image for an element1
backgroundPositionSets or returns the starting position of a background-image1
backgroundRepeatSets or returns how to repeat (tile) a background-image1
backgroundClipSets or returns the painting area of the background3
backgroundOriginSets or returns the positioning area of the background images3
backgroundSizeSets or returns the size of the background image3
backfaceVisibilitySets or returns whether or not an element should be visible when not facing the screen3
borderSets or returns borderWidth, borderStyle, and borderColor in one declaration1
borderBottomSets or returns all the borderBottom properties in one declaration1
borderBottomColorSets or returns the color of the bottom border1
borderBottomLeftRadiusSets or returns the shape of the border of the bottom-left corner3
borderBottomRightRadiusSets or returns the shape of the border of the bottom-right corner3
borderBottomStyleSets or returns the style of the bottom border1
borderBottomWidthSets or returns the width of the bottom border1
borderCollapseSets or returns whether the table border should be collapsed into a single border, or not2
borderColorSets or returns the color of an element’s border (can have up to four values)1
borderImageA shorthand property for setting or returning all the borderImage properties3
borderImageOutsetSets or returns the amount by which the border image area extends beyond the border box3
borderImageRepeatSets or returns whether the image-border should be repeated, rounded or stretched3
borderImageSliceSets or returns the inward offsets of the image-border3
borderImageSourceSets or returns the image to be used as a border3
borderImageWidthSets or returns the widths of the image-border3
borderLeftSets or returns all the borderLeft properties in one declaration1
borderLeftColorSets or returns the color of the left border1
borderLeftStyleSets or returns the style of the left border1
borderLeftWidthSets or returns the width of the left border1
borderRadiusA shorthand property for setting or returning all the four borderRadius properties3
borderRightSets or returns all the borderRight properties in one declaration1
borderRightColorSets or returns the color of the right border1
borderRightStyleSets or returns the style of the right border1
borderRightWidthSets or returns the width of the right border1
borderSpacingSets or returns the space between cells in a table2
borderStyleSets or returns the style of an element’s border (can have up to four values)1
borderTopSets or returns all the borderTop properties in one declaration1
borderTopColorSets or returns the color of the top border1
borderTopLeftRadiusSets or returns the shape of the border of the top-left corner3
borderTopRightRadiusSets or returns the shape of the border of the top-right corner3
borderTopStyleSets or returns the style of the top border1
borderTopWidthSets or returns the width of the top border1
borderWidthSets or returns the width of an element’s border (can have up to four values)1
bottomSets or returns the bottom position of a positioned element2
boxDecorationBreakSets or returns the behaviour of the background and border of an element at page-break, or, for in-line elements, at line-break.3
boxShadowAttaches one or more drop-shadows to the box3
boxSizingAllows you to define certain elements to fit an area in a certain way3
captionSideSets or returns the position of the table caption2
clearSets or returns the position of the element relative to floating objects1
clipSets or returns which part of a positioned element is visible2
colorSets or returns the color of the text1
columnCountSets or returns the number of columns an element should be divided into3
columnFillSets or returns how to fill columns3
columnGapSets or returns the gap between the columns3
columnRuleA shorthand property for setting or returning all the columnRule properties3
columnRuleColorSets or returns the color of the rule between columns3
columnRuleStyleSets or returns the style of the rule between columns3
columnRuleWidthSets or returns the width of the rule between columns3
columnsA shorthand property for setting or returning columnWidth and columnCount3
columnSpanSets or returns how many columns an element should span across3
columnWidthSets or returns the width of the columns3
contentUsed with the :before and :after pseudo-elements, to insert generated content2
counterIncrementIncrements one or more counters2
counterResetCreates or resets one or more counters2
cursorSets or returns the type of cursor to display for the mouse pointer2
directionSets or returns the text direction2
displaySets or returns an element’s display type1
emptyCellsSets or returns whether to show the border and background of empty cells, or not2
filterSets or returns image filters (visual effects, like blur and saturation)3
flexSets or returns the length of the item, relative to the rest3
flexBasisSets or returns the initial length of a flexible item3
flexDirectionSets or returns the direction of the flexible items3
flexFlowA shorthand property for the flexDirection and the flexWrap properties3
flexGrowSets or returns how much the item will grow relative to the rest3
flexShrinkSets or returns how the item will shrink relative to the rest3
flexWrapSets or returns whether the flexible items should wrap or not3
cssFloatSets or returns the horizontal alignment of an element1
fontSets or returns fontStyle, fontVariant, fontWeight, fontSize, lineHeight, and fontFamily in one declaration1
fontFamilySets or returns the font family for text1
fontSizeSets or returns the font size of the text1
fontStyleSets or returns whether the style of the font is normal, italic or oblique1
fontVariantSets or returns whether the font should be displayed in small capital letters1
fontWeightSets or returns the boldness of the font1
fontSizeAdjustPreserves the readability of text when font fallback occurs3
fontStretchSelects a normal, condensed, or expanded face from a font family3
hangingPunctuationSpecifies whether a punctuation character may be placed outside the line box3
heightSets or returns the height of an element1
hyphensSets how to split words to improve the layout of paragraphs3
iconProvides the author the ability to style an element with an iconic equivalent3
imageOrientationSpecifies a rotation in the right or clockwise direction that a user agent applies to an image3
isolationDefines whether an element must create a new stacking content3
justifyContentSets or returns the alignment between the items inside a flexible container when the items do not use all available space.3
leftSets or returns the left position of a positioned element2
letterSpacingSets or returns the space between characters in a text1
lineHeightSets or returns the distance between lines in a text1
listStyleSets or returns listStyleImage, listStylePosition, and listStyleType in one declaration1
listStyleImageSets or returns an image as the list-item marker1
listStylePositionSets or returns the position of the list-item marker1
listStyleTypeSets or returns the list-item marker type1
marginSets or returns the margins of an element (can have up to four values)1
marginBottomSets or returns the bottom margin of an element1
marginLeftSets or returns the left margin of an element1
marginRightSets or returns the right margin of an element1
marginTopSets or returns the top margin of an element1
maxHeightSets or returns the maximum height of an element2
maxWidthSets or returns the maximum width of an element2
minHeightSets or returns the minimum height of an element2
minWidthSets or returns the minimum width of an element2
navDownSets or returns where to navigate when using the arrow-down navigation key3
navIndexSets or returns the tabbing order for an element3
navLeftSets or returns where to navigate when using the arrow-left navigation key3
navRightSets or returns where to navigate when using the arrow-right navigation key3
navUpSets or returns where to navigate when using the arrow-up navigation key3
objectFitSpecifies how the contents of a replaced element should be fitted to the box established by its used height and width3
objectPositionSpecifies the alignment of the replaced element inside its box3
opacitySets or returns the opacity level for an element3
orderSets or returns the order of the flexible item, relative to the rest3
orphansSets or returns the minimum number of lines for an element that must be left at the bottom of a page when a page break occurs inside an element2
outlineSets or returns all the outline properties in one declaration2
outlineColorSets or returns the color of the outline around a element2
outlineOffsetOffsets an outline, and draws it beyond the border edge3
outlineStyleSets or returns the style of the outline around an element2
outlineWidthSets or returns the width of the outline around an element2
overflowSets or returns what to do with content that renders outside the element box2
overflowXSpecifies what to do with the left/right edges of the content, if it overflows the element’s content area3
overflowYSpecifies what to do with the top/bottom edges of the content, if it overflows the element’s content area3
paddingSets or returns the padding of an element (can have up to four values)1
paddingBottomSets or returns the bottom padding of an element1
paddingLeftSets or returns the left padding of an element1
paddingRightSets or returns the right padding of an element1
paddingTopSets or returns the top padding of an element1
pageBreakAfterSets or returns the page-break behavior after an element2
pageBreakBeforeSets or returns the page-break behavior before an element2
pageBreakInsideSets or returns the page-break behavior inside an element2
perspectiveSets or returns the perspective on how 3D elements are viewed3
perspectiveOriginSets or returns the bottom position of 3D elements3
positionSets or returns the type of positioning method used for an element (static, relative, absolute or fixed)2
quotesSets or returns the type of quotation marks for embedded quotations2
resizeSets or returns whether or not an element is resizable by the user3
rightSets or returns the right position of a positioned element2
tableLayoutSets or returns the way to lay out table cells, rows, and columns2
tabSizeSets or returns the length of the tab-character3
textAlignSets or returns the horizontal alignment of text1
textAlignLastSets or returns how the last line of a block or a line right before a forced line break is aligned when text-align is “justify”3
textDecorationSets or returns the decoration of a text1
textDecorationColorSets or returns the color of the text-decoration3
textDecorationLineSets or returns the type of line in a text-decoration3
textDecorationStyleSets or returns the style of the line in a text decoration3
textIndentSets or returns the indentation of the first line of text1
textJustifySets or returns the justification method used when text-align is “justify”3
textOverflowSets or returns what should happen when text overflows the containing element3
textShadowSets or returns the shadow effect of a text3
textTransformSets or returns the capitalization of a text1
topSets or returns the top position of a positioned element2
transformApplies a 2D or 3D transformation to an element3
transformOriginSets or returns the position of transformed elements3
transformStyleSets or returns how nested elements are rendered in 3D space3
transitionA shorthand property for setting or returning the four transition properties3
transitionPropertySets or returns the CSS property that the transition effect is for3
transitionDurationSets or returns how many seconds or milliseconds a transition effect takes to complete3
transitionTimingFunctionSets or returns the speed curve of the transition effect3
transitionDelaySets or returns when the transition effect will start3
unicodeBidiSets or returns whether the text should be overridden to support multiple languages in the same document2
userSelectSets or returns whether the text of an element can be selected or not2
verticalAlignSets or returns the vertical alignment of the content in an element1
visibilitySets or returns whether an element should be visible2
whiteSpaceSets or returns how to handle tabs, line breaks and whitespace in a text1
widthSets or returns the width of an element1
wordBreakSets or returns line breaking rules for non-CJK scripts3
wordSpacingSets or returns the spacing between words in a text1
wordWrapAllows long, unbreakable words to be broken and wrap to the next line3
widowsSets or returns the minimum number of lines for an element that must be visible at the top of a page2
zIndexSets or returns the stack order of a positioned element2

访问样式对象

可以从文档的头部或特定的HTML元素访问Style对象。

  • 从文档的头部访问样式对象: 例如: var x = document.getElementsByTagName("STYLE");
  • 访问指定元素的样式对象: 例 var x = document.getElementById("myH1").style;

创建样式对象

  • 您可以使用document.createElement()方法创建元素: 例 var x = document.createElement("STYLE");
  • 您还可以设置现有元素的样式属性: 例 document.getElementById("myH1").style.color = "red";

windows窗口对象

窗口对象表示浏览器中打开的窗口。

如果文档包含框架(标记),则浏览器将为HTML文档创建一个窗口对象,并为每个框架创建一个其他窗口对象。

注意:没有适用于windows对象的公共标准,但是所有主要的浏览器都支持它。

windows窗口对象属性

PropertyDescription
closedReturns a Boolean value indicating whether a window has been closed or not
consoleReturns a reference to the Console object, which provides methods for logging information to the browser’s console (See Console object)
defaultStatusSets or returns the default text in the statusbar of a window
documentReturns the Document object for the window (See Document object)
frameElementReturns the <iframe> element in which the current window is inserted
framesReturns all <iframe> elements in the current window
historyReturns the History object for the window (See History object)
innerHeightReturns the height of the window’s content area (viewport) including scrollbars
innerWidthReturns the width of a window’s content area (viewport) including scrollbars
lengthReturns the number of <iframe> elements in the current window
localStorageAllows to save key/value pairs in a web browser. Stores the data with no expiration date
locationReturns the Location object for the window (See Location object)
nameSets or returns the name of a window
navigatorReturns the Navigator object for the window (See Navigator object)
openerReturns a reference to the window that created the window
outerHeightReturns the height of the browser window, including toolbars/scrollbars
outerWidthReturns the width of the browser window, including toolbars/scrollbars
pageXOffsetReturns the pixels the current document has been scrolled (horizontally) from the upper left corner of the window
pageYOffsetReturns the pixels the current document has been scrolled (vertically) from the upper left corner of the window
parentReturns the parent window of the current window
screenReturns the Screen object for the window (See Screen object)
screenLeftReturns the horizontal coordinate of the window relative to the screen
screenTopReturns the vertical coordinate of the window relative to the screen
screenXReturns the horizontal coordinate of the window relative to the screen
screenYReturns the vertical coordinate of the window relative to the screen
sessionStorageAllows to save key/value pairs in a web browser. Stores the data for one session
scrollXAn alias of pageXOffset
scrollYAn alias of pageYOffset
selfReturns the current window
statusSets or returns the text in the statusbar of a window
topReturns the topmost browser window

### windows窗口对象方法

MethodDescription
alert()Displays an alert box with a message and an OK button
atob()Decodes a base-64 encoded string
blur()Removes focus from the current window
btoa()Encodes a string in base-64
clearInterval()Clears a timer set with setInterval()
clearTimeout()Clears a timer set with setTimeout()
close()Closes the current window
confirm()Displays a dialog box with a message and an OK and a Cancel button
focus()Sets focus to the current window
getComputedStyle()Gets the current computed CSS styles applied to an element
getSelection()Returns a Selection object representing the range of text selected by the user
matchMedia()Returns a MediaQueryList object representing the specified CSS media query string
moveBy()Moves a window relative to its current position
moveTo()Moves a window to the specified position
open()Opens a new browser window
print()Prints the content of the current window
prompt()Displays a dialog box that prompts the visitor for input
requestAnimationFrame()Requests the browser to call a function to update an animation before the next repaint
resizeBy()Resizes the window by the specified pixels
resizeTo()Resizes the window to the specified width and height
scroll()Deprecated. This method has been replaced by the scrollTo() method.
scrollBy()Scrolls the document by the specified number of pixels
scrollTo()Scrolls the document to the specified coordinates
setInterval()Calls a function or evaluates an expression at specified intervals (in milliseconds)
setTimeout()Calls a function or evaluates an expression after a specified number of milliseconds
stop()Stops the window from loading

原文作者: 根叔

原始链接: https://www.learnhard.cn/python_spider/006.html_dom%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86/

发表时间: 2024-05-31 12:51:22 +0800 CST

版权声明:本文采用知识共享署名-非商业性使用 4.0 国际许可协议进行许可