JavaScript Node Properties: Type, Tag, and Contents
In the Document Object Model (DOM), everything in an HTML page is a node (elements, text, attributes, comments, etc.). JavaScript allows us to access and modify these nodes using various node properties.
1️⃣ Node Type (nodeType)
Every node in the DOM has a numeric type value that identifies what kind of node it is.
📌 Common nodeType Values
| Node Type | Value | Example |
|---|---|---|
| Element Node | 1 | <div>, <p> |
| Text Node | 3 | "Hello" inside <p>Hello</p> |
| Comment Node | 8 | <!-- This is a comment --> |
| Document Node | 9 | The document itself |
📌 Example: Get Node Type
🔹 element.firstChild gets the first child, which is usually a Text Node (even whitespace).
2️⃣ Node Tag Name (nodeName and tagName)
nodeNamereturns the name of the node (uppercase for elements).tagNamereturns the element’s tag name (only for elements).
📌 Example: Get Tag Name
🔹 For non-element nodes, nodeName returns different values:
- Text node →
#text - Comment node →
#comment - Document node →
#document
3️⃣ Node Content (innerHTML, textContent, innerText)
📌 innerHTML (HTML Content)
- Gets/sets HTML inside an element.
- Includes all HTML tags.
📌 textContent (Pure Text)
- Gets/sets only text (ignores HTML).
- Includes hidden elements' text.
📌 innerText (Visible Text)
- Gets/sets only visible text.
- Ignores hidden text (CSS
display: none).
4️⃣ Full Example
🚀 Summary
| Property | Description |
|---|---|
nodeType | Returns a numeric value representing the type of node. |
nodeName | Returns the name of the node (e.g., "DIV", "#text"). |
tagName | Returns the tag name of an element (only for elements). |
innerHTML | Gets/sets the HTML inside an element. |
textContent | Gets/sets only text (ignores hidden text). |
innerText | Gets/sets only visible text (ignores hidden elements). |
🚀 Now you can manipulate and access DOM nodes easily! 🎯
Need more details? Let me know! 🚀
