- Свойства узлов: тип, тег и содержимое
- Классы DOM-узлов
- Determine element’s type with JavaScript/jQuery
- 1. Using JavaScript
- JS
- HTML
- JS
- HTML
- JS
- HTML
- 2. Using jQuery
- JS
- HTML
- JS
- HTML
- Node properties: type, tag and contents
- DOM node classes
- Node: nodeType property
- Value
- Examples
- Different types of nodes
- Comments
- Specifications
- Browser compatibility
- Found a content problem with this page?
Свойства узлов: тип, тег и содержимое
Теперь давайте более внимательно взглянем на 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 содержится его имя:
Determine element’s type with JavaScript/jQuery
This post will discuss how to determine the element’s type in JavaScript and jQuery.
1. Using JavaScript
The tagName property returns the element’s tag name in upper-case for HTML documents. For example, tagName returns DIV when called on a element.
JS
HTML
Alternatively, you can use the nodeName property that returns the current Node’s name, which is the same as tagName for an element.
JS
HTML
Note when called on an element, both the tagName or nodeName property returns INPUT, which doesn’t tell whether the input is a text box or a checkbox or a radio button. However, you can use the type attribute for this purpose:
JS
HTML
2. Using jQuery
With jQuery, you can use the .prop() method to get the value of tagName or nodeName or type property.
JS
HTML
If you just need to check for the specific type of element, you can use the .is() method, which returns a Boolean value:
JS
HTML
That’s all about checking an element’s type in JavaScript and jQuery.
Average rating 4.67 /5. Vote count: 24
No votes so far! Be the first to rate this post.
We are sorry that this post was not useful for you!
Tell us how we can improve this post?
Thanks for reading.
Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and help us grow. Happy coding 🙂
This website uses cookies. By using this site, you agree to the use of cookies, our policies, copyright terms and other conditions. Read our Privacy Policy. Got it
Node properties: type, tag and contents
In this chapter we’ll see more into what they are and learn their most used properties.
DOM node classes
Each DOM node belongs to the corresponding built-in class.
The root of the hierarchy is EventTarget, that is inherited by Node, and other DOM nodes inherit from it.
Here’s the picture, explanations to follow:
- EventTarget – is the root “abstract” class for everything. Objects of that class are never created. It serves as a base, so that all DOM nodes support so-called “events”, we’ll study them later.
- Node – is also an “abstract” class, serving as a base for DOM nodes. It provides the core tree functionality: parentNode , nextSibling , childNodes and so on (they are getters). Objects of Node class are never created. But there are other classes that inherit from it (and so inherit the Node functionality).
- Document, for historical reasons often inherited by HTMLDocument (though the latest spec doesn’t dictate it) – is a document as a whole. The document global object belongs exactly to this class. It serves as an entry point to the DOM.
- CharacterData – an “abstract” class, inherited by:
- Text – the class corresponding to a text inside elements, e.g. Hello in
Hello
.
- Comment – the class for comments. They are not shown, but each comment becomes a member of DOM.
- HTMLInputElement – the class for elements,
- HTMLBodyElement – the class for elements,
- HTMLAnchorElement – the class for elements,
- …and so on.
There are many other tags with their own classes that may have specific properties and methods, while some elements, such as , , do not have any specific properties, so they are instances of HTMLElement class.
So, the full set of properties and methods of a given node comes as the result of the chain of inheritance.
For example, let’s consider the DOM object for an element. It belongs to HTMLInputElement class.
It gets properties and methods as a superposition of (listed in inheritance order):
- HTMLInputElement – this class provides input-specific properties,
- HTMLElement – it provides common HTML element methods (and getters/setters),
- Element – provides generic element methods,
- Node – provides common DOM node properties,
- EventTarget – gives the support for events (to be covered),
- …and finally it inherits from Object , so “plain object” methods like hasOwnProperty are also available.
To see the DOM node class name, we can recall that an object usually has the constructor property. It references the class constructor, and constructor.name is its name:
Node: nodeType property
The read-only nodeType property of a Node interface is an integer that identifies what the node is. It distinguishes different kind of nodes from each other, such as elements , text and comments .
Value
An integer which specifies the type of the node. Possible values are:
The actual Text inside an Element or Attr .
The following constants have been deprecated and are not in use anymore: Node.ENTITY_REFERENCE_NODE ( 5 ), Node.ENTITY_NODE ( 6 ), and Node.NOTATION_NODE ( 12 ).
Examples
Different types of nodes
.nodeType === Node.DOCUMENT_NODE; // true document.doctype.nodeType === Node.DOCUMENT_TYPE_NODE; // true document.createDocumentFragment().nodeType === Node.DOCUMENT_FRAGMENT_NODE; // true const p = document.createElement("p"); p.textContent = "Once upon a time…"; p.nodeType === Node.ELEMENT_NODE; // true p.firstChild.nodeType === Node.TEXT_NODE; // true
Comments
This example checks if the first node inside the document element is a comment, and displays a message if not.
const node = document.documentElement.firstChild; if (node.nodeType !== Node.COMMENT_NODE) console.warn("You should comment your code!"); >
Specifications
Browser compatibility
BCD tables only load in the browser
Found a content problem with this page?
This page was last modified on Apr 7, 2023 by MDN contributors.
Your blueprint for a better internet.
- Text – the class corresponding to a text inside elements, e.g. Hello in
- Text – класс, соответствующий тексту внутри элементов. Например, Hello в