Свойства узлов: тип, тег и содержимое
Теперь давайте более внимательно взглянем на DOM-узлы.
В этой главе мы подробнее разберём, что они собой представляют и изучим их основные свойства.
Классы DOM-узлов
Каждый DOM-узел принадлежит соответствующему встроенному классу.
Корнем иерархии является EventTarget, от него наследует Node и остальные DOM-узлы.
На рисунке ниже изображены основные классы:
Существуют следующие классы:
- EventTarget – это корневой «абстрактный» класс для всего. Объекты этого класса никогда не создаются. Он служит основой, благодаря которой все DOM-узлы поддерживают так называемые «события», о которых мы поговорим позже.
- Node – также является «абстрактным» классом, и служит основой для DOM-узлов. Он обеспечивает базовую функциональность: parentNode , nextSibling , childNodes и т.д. (это геттеры). Объекты класса Node никогда не создаются. Но есть определённые классы узлов, которые наследуются от него (и следовательно наследуют функционал Node ).
- Document, по историческим причинам часто наследуется HTMLDocument (хотя последняя спецификация этого не навязывает) – это документ в целом. Глобальный объект document принадлежит именно к этому классу. Он служит точкой входа в DOM.
- CharacterData – «абстрактный» класс. Вот, кем он наследуется:
- Text – класс, соответствующий тексту внутри элементов. Например, Hello в
Hello
.
- Comment – класс для комментариев. Они не отображаются, но каждый комментарий становится членом DOM.
- HTMLInputElement – класс для тега ,
- HTMLBodyElement – класс для тега ,
- HTMLAnchorElement – класс для тега ,
- …и т.д.
Также существует множество других тегов со своими собственными классами, которые могут иметь определенные свойства и методы, в то время как некоторые элементы, такие как , и , не имеют каких-либо определенных свойств, поэтому они являются экземплярами класса HTMLElement .
Таким образом, полный набор свойств и методов данного узла является результатом цепочки наследования.
Рассмотрим DOM-объект для тега . Он принадлежит классу HTMLInputElement.
Он получает свойства и методы из (в порядке наследования):
- HTMLInputElement – этот класс предоставляет специфичные для элементов формы свойства,
- HTMLElement – предоставляет общие для HTML-элементов методы (и геттеры/сеттеры),
- Element – предоставляет типовые методы элемента,
- Node – предоставляет общие свойства DOM-узлов,
- EventTarget – обеспечивает поддержку событий (поговорим о них дальше),
- …и, наконец, он наследует от Object , поэтому доступны также методы «обычного объекта», такие как hasOwnProperty .
Для того, чтобы узнать имя класса DOM-узла, вспомним, что обычно у объекта есть свойство constructor . Оно ссылается на конструктор класса, и в свойстве constructor.name содержится его имя:
HTMLElement
The HTMLElement interface represents any HTML element. Some elements directly implement this interface, while others implement it via an interface that inherits it.
Instance properties
Inherits properties from its parent, Element . HTMLElement.accessKey A string representing the access key assigned to the element. HTMLElement.accessKeyLabel Read only Returns a string containing the element’s assigned access key. HTMLElement.attributeStyleMap Read only A StylePropertyMap representing the declarations of the element’s style attribute. HTMLElement.contentEditable A string, where a value of true means the element is editable and a value of false means it isn’t. HTMLElement.isContentEditable Read only Returns a boolean value indicating whether or not the content of the element can be edited. HTMLElement.dataset Read only Returns a DOMStringMap with which script can read and write the element’s custom data attributes ( data-* ) . HTMLElement.dir A string, reflecting the dir global attribute, representing the directionality of the element. Possible values are «ltr» , «rtl» , and «auto» . HTMLElement.draggable A boolean value indicating if the element can be dragged. HTMLElement.enterKeyHint A string defining what action label (or icon) to present for the enter key on virtual keyboards. HTMLElement.hidden A string or boolean value reflecting the value of the element’s hidden attribute. HTMLElement.inert A boolean value indicating whether the user agent must act as though the given node is absent for the purposes of user interaction events, in-page text searches («find in page»), and text selection. HTMLElement.innerText Represents the rendered text content of a node and its descendants. As a getter, it approximates the text the user would get if they highlighted the contents of the element with the cursor and then copied it to the clipboard. As a setter, it replaces the content inside the selected element, converting any line breaks into elements. HTMLElement.inputMode A string value reflecting the value of the element’s inputmode attribute. HTMLElement.popover Gets and sets an element’s popover state via JavaScript ( «auto» or «manual» ), and can be used for feature detection. Reflects the value of the popover global HTML attribute. HTMLElement.lang A string representing the language of an element’s attributes, text, and element contents. HTMLElement.noModule A boolean value indicating whether an import script can be executed in user agents that support module scripts. HTMLElement.nonce Returns the cryptographic number used once that is used by Content Security Policy to determine whether a given fetch will be allowed to proceed. HTMLElement.offsetHeight Read only Returns a double containing the height of an element, relative to the layout. HTMLElement.offsetLeft Read only Returns a double , the distance from this element’s left border to its offsetParent ‘s left border. HTMLElement.offsetParent Read only An Element that is the element from which all offset calculations are currently computed. HTMLElement.offsetTop Read only Returns a double , the distance from this element’s top border to its offsetParent ‘s top border. HTMLElement.offsetWidth Read only Returns a double containing the width of an element, relative to the layout. HTMLElement.outerText Represents the rendered text content of a node and its descendants. As a getter, it is the same as HTMLElement.innerText (it represents the rendered text content of an element and its descendants). As a setter, it replaces the selected node and its contents with the given value, converting any line breaks into elements. HTMLElement.properties Experimental Read only Returns a HTMLPropertiesCollection … HTMLElement.spellcheck A boolean value that controls spell-checking. It is present on all HTML elements, though it doesn’t have an effect on all of them. HTMLElement.style A CSSStyleDeclaration representing the declarations of the element’s style attribute. HTMLElement.tabIndex A long representing the position of the element in the tabbing order. HTMLElement.title A string containing the text that appears in a popup box when mouse is over the element. HTMLElement.translate A boolean value representing the translation.
Instance methods
Inherits methods from its parent, Element . HTMLElement.attachInternals() Returns an ElementInternals object, and enables a custom element to participate in HTML forms. HTMLElement.blur() Removes keyboard focus from the currently focused element. HTMLElement.click() Sends a mouse click event to the element. HTMLElement.focus() Makes the element the current keyboard focus. HTMLElement.hidePopover() Hides a popover element by removing it from the top layer and styling it with display: none . HTMLElement.showPopover() Shows a popover element by adding it to the top layer and removing display: none; from its styles. HTMLElement.togglePopover() Toggles a popover element between the hidden and showing states.
Events
Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface. copy Fired when the user initiates a copy action through the browser’s user interface. cut Fired when the user initiates a cut action through the browser’s user interface. paste Fired when the user initiates a paste action through the browser’s user interface. invalid Fired when an element does not satisfy its constraints during constraint validation. beforetoggle Fired when the element is a popover, before it is hidden or shown. toggle Fired when the element is a popover, just after it is hidden or shown.
Animation events
animationcancel Fired when an animation unexpectedly aborts. animationend Fired when an animation has completed normally. animationiteration Fired when an animation iteration has completed. animationstart Fired when an animation starts.
Input events
beforeinput Fired when the value of an , , or element is about to be modified. input Fired when the value of an , , or element has been changed. change Fired when the value of an , , or element has been changed and committed by the user. Unlike the input event, the change event is not necessarily fired for each alteration to an element’s value .
Pointer events
gotpointercapture Fired when an element captures a pointer using setPointerCapture() . lostpointercapture Fired when a captured pointer is released. pointercancel Fired when a pointer event is canceled. pointerdown Fired when a pointer becomes active. pointerenter Fired when a pointer is moved into the hit test boundaries of an element or one of its descendants. pointerleave Fired when a pointer is moved out of the hit test boundaries of an element. pointermove Fired when a pointer changes coordinates. pointerout Fired when a pointer is moved out of the hit test boundaries of an element (among other reasons). pointerover Fired when a pointer is moved into an element’s hit test boundaries. pointerup Fired when a pointer is no longer active.
Transition events
transitioncancel Fired when a CSS transition is canceled. transitionend Fired when a CSS transition has completed. transitionrun Fired when a CSS transition is first created. transitionstart Fired when a CSS transition has actually started.
Specifications
- Text – класс, соответствующий тексту внутри элементов. Например, Hello в