Node types and attributes
In JavaScript, nodes are the fundamental building blocks of the DOM tree, with different types of nodes possessing distinct properties and behaviors. Understanding node types and their attributes is crucial for manipulating the DOM.
Overview of Node Types
The DOM specification defines various node types, each corresponding to a numeric constant:
Node.ELEMENT_NODE (1)
Node.ATTRIBUTE_NODE (2)
Node.TEXT_NODE (3)
Node.CDATA_SECTION_NODE (4)
Node.PROCESSING_INSTRUCTION_NODE (7)
Node.COMMENT_NODE (8)
Node.DOCUMENT_NODE (9)
Node.DOCUMENT_TYPE_NODE (10)
Node.DOCUMENT_FRAGMENT_NODE (11)
You can determine a node's type using its nodeType
property:
const element = document.createElement('div');
console.log(element.nodeType === Node.ELEMENT_NODE); // true
console.log(element.nodeType); // 1
Element Nodes
Element nodes are the most common type, representing tags in HTML or XML documents. Their characteristics include:
nodeType
is 1nodeName
returns the tag name (uppercase)- Has a
tagName
property - Can contain child nodes and attributes
const div = document.createElement('div');
div.id = 'container';
div.className = 'box';
div.setAttribute('data-custom', 'value');
console.log(div.nodeName); // "DIV"
console.log(div.tagName); // "DIV"
console.log(div.id); // "container"
console.log(div.className); // "box"
console.log(div.getAttribute('data-custom')); // "value"
Text Nodes
Text nodes contain textual content within the document:
nodeType
is 3nodeName
returns "#text"- Data is stored in the
nodeValue
ordata
property
const textNode = document.createTextNode('Hello World');
console.log(textNode.nodeType); // 3
console.log(textNode.nodeName); // "#text"
console.log(textNode.data); // "Hello World"
console.log(textNode.nodeValue); // "Hello World"
// Modify text content
textNode.appendData('!');
textNode.nodeValue = 'Changed text';
Attribute Nodes
Attribute nodes represent element attributes, though they are rarely used directly in modern DOM manipulation:
nodeType
is 2nodeName
returns the attribute namenodeValue
returns the attribute value
const attr = document.createAttribute('custom');
attr.value = 'some value';
console.log(attr.nodeType); // 2
console.log(attr.nodeName); // "custom"
console.log(attr.nodeValue); // "some value"
Comment Nodes
Comment nodes represent comments in HTML documents:
nodeType
is 8nodeName
returns "#comment"- Comment content is stored in the
nodeValue
ordata
property
const comment = document.createComment('This is a comment');
console.log(comment.nodeType); // 8
console.log(comment.nodeName); // "#comment"
console.log(comment.data); // "This is a comment"
Document Nodes
Document nodes represent the entire document:
nodeType
is 9nodeName
returns "#document"- Serves as the root node of the DOM tree
console.log(document.nodeType); // 9
console.log(document.nodeName); // "#document"
console.log(document.documentElement); // <html> element
Document Fragment Nodes
Document fragments are lightweight document objects used for efficiently manipulating multiple nodes:
nodeType
is 11nodeName
returns "#document-fragment"- Not rendered in the main DOM tree
const fragment = document.createDocumentFragment();
const ul = document.createElement('ul');
for (let i = 0; i < 3; i++) {
const li = document.createElement('li');
li.textContent = `Item ${i + 1}`;
fragment.appendChild(li);
}
ul.appendChild(fragment);
document.body.appendChild(ul);
Node Properties and Methods
All node types inherit from the Node interface and share the following common properties and methods:
Basic Properties
const element = document.getElementById('example');
console.log(element.nodeName); // Node name
console.log(element.nodeType); // Node type
console.log(element.nodeValue); // Node value
console.log(element.parentNode); // Parent node
console.log(element.childNodes); // Child node list
console.log(element.firstChild); // First child node
console.log(element.lastChild); // Last child node
console.log(element.previousSibling); // Previous sibling node
console.log(element.nextSibling); // Next sibling node
Manipulation Methods
// Create and add nodes
const newElement = document.createElement('div');
const textNode = document.createTextNode('Some text');
newElement.appendChild(textNode);
// Clone nodes
const clonedNode = newElement.cloneNode(true); // Deep clone
// Insert nodes
const referenceNode = document.getElementById('reference');
referenceNode.parentNode.insertBefore(newElement, referenceNode);
// Replace nodes
referenceNode.parentNode.replaceChild(clonedNode, referenceNode);
// Remove nodes
clonedNode.parentNode.removeChild(clonedNode);
Node Traversal
The DOM provides multiple methods for traversing the node tree:
// Depth-first traversal
function traverse(node) {
console.log(node.nodeName);
for (let i = 0; i < node.childNodes.length; i++) {
traverse(node.childNodes[i]);
}
}
// Using the TreeWalker API
const walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_ELEMENT,
null,
false
);
let currentNode;
while (currentNode = walker.nextNode()) {
console.log(currentNode.tagName);
}
Modern DOM Manipulation
Modern JavaScript offers more concise ways to manipulate the DOM:
// Query selection
const elements = document.querySelectorAll('.class-selector');
const element = document.querySelector('#id-selector');
// classList operations
element.classList.add('new-class');
element.classList.remove('old-class');
element.classList.toggle('active');
// Dataset access
element.dataset.customValue = 'data';
// Style manipulation
element.style.setProperty('--custom-property', 'value');
Node Comparison
You can compare nodes using the isEqualNode
and isSameNode
methods:
const div1 = document.createElement('div');
div1.className = 'box';
const div2 = div1.cloneNode(true);
console.log(div1.isEqualNode(div2)); // true
console.log(div1.isSameNode(div2)); // false
console.log(div1.isSameNode(div1)); // true
Custom Element Nodes
Modern browsers support creating custom elements:
class MyElement extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<style>
:host {
display: block;
border: 1px solid #ccc;
}
</style>
<slot></slot>
`;
}
}
customElements.define('my-element', MyElement);
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn