javascript
examples
examples.js⚡javascript
/**
* ========================================
* 10.1 DOM BASICS - CODE EXAMPLES
* ========================================
*
* NOTE: These examples are designed for browser environment.
* To run them, create an HTML file and include this script,
* or use browser developer tools console.
*/
/**
* EXAMPLE 1: Basic DOM Structure
*
* HTML for this example:
* <div id="container">
* <h1>Title</h1>
* <p class="content">Hello World</p>
* </div>
*/
console.log('--- Example 1: DOM Structure ---');
// In browser:
// const container = document.getElementById('container');
// console.log(container.nodeType); // 1 (Element)
// console.log(container.nodeName); // "DIV"
// console.log(container.childNodes); // NodeList of children
// Simulating structure understanding:
const domStructure = {
nodeType: 1,
nodeName: 'DIV',
id: 'container',
children: [
{ nodeType: 1, nodeName: 'H1', textContent: 'Title' },
{
nodeType: 1,
nodeName: 'P',
className: 'content',
textContent: 'Hello World',
},
],
};
console.log('DOM structure representation:', domStructure);
/**
* EXAMPLE 2: getElementById
*/
console.log('\n--- Example 2: getElementById ---');
// HTML: <div id="header">Header Content</div>
// In browser:
// const header = document.getElementById('header');
// console.log(header.textContent); // "Header Content"
// Returns null if not found
// const notFound = document.getElementById('nonexistent');
// console.log(notFound); // null
console.log('getElementById returns single element or null');
console.log('Fastest selection method for IDs');
/**
* EXAMPLE 3: querySelector
*/
console.log('\n--- Example 3: querySelector ---');
// Various selector examples:
const selectors = [
'#header', // By ID
'.nav-item', // By class
'button', // By tag
"input[type='email']", // By attribute
'.container > .item', // Child combinator
'ul li:first-child', // Pseudo-selector
'[data-role="admin"]', // Data attribute
'.card:not(.hidden)', // Negation
];
console.log('querySelector accepts any CSS selector:');
selectors.forEach((sel) => console.log(` document.querySelector('${sel}')`));
/**
* EXAMPLE 4: querySelectorAll
*/
console.log('\n--- Example 4: querySelectorAll ---');
// HTML:
// <ul>
// <li class="item">One</li>
// <li class="item">Two</li>
// <li class="item">Three</li>
// </ul>
// In browser:
// const items = document.querySelectorAll('.item');
// console.log(items.length); // 3
// // Iterate with forEach
// items.forEach((item, index) => {
// console.log(`Item ${index}: ${item.textContent}`);
// });
// // Convert to array for more methods
// const itemsArray = Array.from(items);
// const filtered = itemsArray.filter(item => item.textContent.includes('o'));
console.log('querySelectorAll returns NodeList');
console.log('NodeList supports forEach and for...of');
console.log('Convert to array for filter, map, reduce');
/**
* EXAMPLE 5: getElementsByClassName (Live Collection)
*/
console.log('\n--- Example 5: Live vs Static Collections ---');
// Demonstrating the difference:
// const container = document.getElementById('container');
// Static collection (querySelectorAll)
// const staticItems = container.querySelectorAll('.item');
// console.log('Static count:', staticItems.length); // e.g., 2
// Live collection (getElementsByClassName)
// const liveItems = container.getElementsByClassName('item');
// console.log('Live count:', liveItems.length); // e.g., 2
// Add new element
// const newItem = document.createElement('div');
// newItem.className = 'item';
// container.appendChild(newItem);
// console.log('Static count after add:', staticItems.length); // Still 2!
// console.log('Live count after add:', liveItems.length); // Now 3!
console.log('Static (querySelectorAll): Snapshot at query time');
console.log('Live (getElementsBy*): Updates automatically');
/**
* EXAMPLE 6: Parent Traversal
*/
console.log('\n--- Example 6: Parent Traversal ---');
// HTML:
// <div class="grandparent">
// <div class="parent">
// <span class="child">Text</span>
// </div>
// </div>
// In browser:
// const child = document.querySelector('.child');
// // Direct parent
// const parent = child.parentElement;
// console.log(parent.className); // "parent"
// // Grandparent
// const grandparent = child.parentElement.parentElement;
// console.log(grandparent.className); // "grandparent"
// // Find closest ancestor matching selector
// const closestDiv = child.closest('div');
// console.log(closestDiv.className); // "parent" (nearest div)
// const closestGrand = child.closest('.grandparent');
// console.log(closestGrand.className); // "grandparent"
console.log('parentElement - direct parent');
console.log('closest(selector) - nearest ancestor matching selector');
/**
* EXAMPLE 7: Child Traversal
*/
console.log('\n--- Example 7: Child Traversal ---');
// HTML:
// <ul id="list">
// <li>First</li>
// <li>Second</li>
// <li>Third</li>
// </ul>
// In browser:
// const list = document.getElementById('list');
// // Element children
// console.log(list.firstElementChild.textContent); // "First"
// console.log(list.lastElementChild.textContent); // "Third"
// console.log(list.children.length); // 3
// // All children (including text nodes)
// console.log(list.childNodes.length); // May be more due to whitespace
// // Iterate children
// for (const child of list.children) {
// console.log(child.textContent);
// }
console.log('children - HTMLCollection of element children');
console.log('childNodes - includes text nodes (whitespace)');
console.log('firstElementChild/lastElementChild - first/last element');
/**
* EXAMPLE 8: Sibling Traversal
*/
console.log('\n--- Example 8: Sibling Traversal ---');
// HTML:
// <div class="first">First</div>
// <div class="middle">Middle</div>
// <div class="last">Last</div>
// In browser:
// const middle = document.querySelector('.middle');
// // Previous sibling
// const prev = middle.previousElementSibling;
// console.log(prev.className); // "first"
// // Next sibling
// const next = middle.nextElementSibling;
// console.log(next.className); // "last"
// // Get all siblings (custom function)
// function getAllSiblings(element) {
// return Array.from(element.parentElement.children)
// .filter(child => child !== element);
// }
console.log('previousElementSibling - element before');
console.log('nextElementSibling - element after');
/**
* EXAMPLE 9: textContent vs innerHTML
*/
console.log('\n--- Example 9: textContent vs innerHTML ---');
// HTML: <div id="test"><strong>Hello</strong> World</div>
// In browser:
// const div = document.getElementById('test');
// // innerHTML returns/sets HTML
// console.log(div.innerHTML); // "<strong>Hello</strong> World"
// // textContent returns/sets text only
// console.log(div.textContent); // "Hello World"
// // Setting values
// div.innerHTML = '<em>New</em> Content'; // Parses HTML
// div.textContent = '<em>New</em> Content'; // Displays as text
// Security example:
const userInput = '<script>alert("XSS")</script>';
console.log('User input:', userInput);
console.log('With textContent: displayed as plain text (SAFE)');
console.log('With innerHTML: could execute script (DANGEROUS)');
/**
* EXAMPLE 10: classList API
*/
console.log('\n--- Example 10: classList API ---');
// In browser:
// const box = document.querySelector('.box');
// // Add classes
// box.classList.add('active');
// box.classList.add('visible', 'highlighted'); // Multiple
// // Remove classes
// box.classList.remove('hidden');
// // Toggle class
// box.classList.toggle('dark'); // Add if missing, remove if present
// box.classList.toggle('featured', true); // Force add
// box.classList.toggle('featured', false); // Force remove
// // Check for class
// if (box.classList.contains('active')) {
// console.log('Box is active');
// }
// // Replace class
// box.classList.replace('old', 'new');
// // List all classes
// console.log([...box.classList]); // Array of class names
const classListMethods = [
'add(class1, class2, ...)',
'remove(class1, class2, ...)',
'toggle(class)',
'toggle(class, force)',
'contains(class)',
'replace(old, new)',
'item(index)',
];
console.log('classList methods:');
classListMethods.forEach((m) => console.log(` ${m}`));
/**
* EXAMPLE 11: Attributes
*/
console.log('\n--- Example 11: Working with Attributes ---');
// HTML: <a id="link" href="/page" target="_blank" data-id="123">Link</a>
// In browser:
// const link = document.getElementById('link');
// // Get attribute
// console.log(link.getAttribute('href')); // "/page"
// console.log(link.getAttribute('target')); // "_blank"
// // Set attribute
// link.setAttribute('href', '/new-page');
// link.setAttribute('title', 'Click me');
// // Check existence
// console.log(link.hasAttribute('target')); // true
// // Remove attribute
// link.removeAttribute('target');
// // Data attributes (special handling)
// console.log(link.dataset.id); // "123"
// link.dataset.category = 'news'; // Sets data-category="news"
// link.dataset.userName = 'john'; // Sets data-user-name="john"
console.log('getAttribute/setAttribute for standard attributes');
console.log('dataset property for data-* attributes');
console.log('data-user-name in HTML becomes dataset.userName in JS');
/**
* EXAMPLE 12: Node Properties
*/
console.log('\n--- Example 12: Node Properties ---');
// nodeType values
const nodeTypes = {
ELEMENT_NODE: 1,
TEXT_NODE: 3,
COMMENT_NODE: 8,
DOCUMENT_NODE: 9,
DOCUMENT_FRAGMENT_NODE: 11,
};
console.log('Common nodeType values:');
Object.entries(nodeTypes).forEach(([name, value]) => {
console.log(` ${name}: ${value}`);
});
// In browser:
// const element = document.querySelector('div');
// console.log(element.nodeType); // 1
// console.log(element.nodeName); // "DIV"
// console.log(element.tagName); // "DIV"
/**
* EXAMPLE 13: Document Properties
*/
console.log('\n--- Example 13: Document Properties ---');
// In browser:
// console.log(document.documentElement); // <html>
// console.log(document.head); // <head>
// console.log(document.body); // <body>
// console.log(document.title); // Page title
// console.log(document.URL); // Current URL
// console.log(document.domain); // Domain
// console.log(document.referrer); // Previous page
// // Collections
// console.log(document.forms); // All forms
// console.log(document.images); // All images
// console.log(document.links); // All links with href
console.log('document.documentElement - <html> element');
console.log('document.head - <head> element');
console.log('document.body - <body> element');
console.log('document.forms/images/links - live collections');
/**
* EXAMPLE 14: Checking Element State
*/
console.log('\n--- Example 14: Element State ---');
// In browser:
// const element = document.querySelector('.item');
// // Check if has children
// console.log(element.hasChildNodes()); // true/false
// console.log(element.children.length > 0); // Alternative
// // Check if matches selector
// console.log(element.matches('.item')); // true
// console.log(element.matches('.active')); // depends on classes
// // Check if contains another element
// const child = element.querySelector('span');
// console.log(element.contains(child)); // true
console.log('hasChildNodes() - check for children');
console.log('matches(selector) - check if element matches');
console.log('contains(element) - check if contains another element');
/**
* EXAMPLE 15: Getting Element Dimensions
*/
console.log('\n--- Example 15: Element Dimensions ---');
// In browser:
// const box = document.querySelector('.box');
// // Content dimensions (without padding/border)
// console.log(box.clientWidth, box.clientHeight);
// // Including border
// console.log(box.offsetWidth, box.offsetHeight);
// // Scroll dimensions
// console.log(box.scrollWidth, box.scrollHeight);
// console.log(box.scrollTop, box.scrollLeft);
// // Bounding rectangle
// const rect = box.getBoundingClientRect();
// console.log(rect.top, rect.left);
// console.log(rect.width, rect.height);
// console.log(rect.bottom, rect.right);
console.log('clientWidth/Height - content + padding');
console.log('offsetWidth/Height - content + padding + border');
console.log('getBoundingClientRect() - position relative to viewport');
/**
* EXAMPLE 16: Computed Styles
*/
console.log('\n--- Example 16: Computed Styles ---');
// In browser:
// const element = document.querySelector('.styled');
// // Get computed style
// const styles = getComputedStyle(element);
// console.log(styles.color); // "rgb(0, 0, 0)"
// console.log(styles.fontSize); // "16px"
// console.log(styles.display); // "block"
// // Inline styles
// console.log(element.style.color); // Only if set inline
console.log('getComputedStyle() - all computed CSS values');
console.log('element.style - only inline styles');
/**
* EXAMPLE 17: Scoped Queries
*/
console.log('\n--- Example 17: Scoped Queries ---');
// HTML:
// <div id="container1">
// <span class="item">Item 1</span>
// </div>
// <div id="container2">
// <span class="item">Item 2</span>
// </div>
// In browser:
// // Query within specific container
// const container1 = document.getElementById('container1');
// const item1 = container1.querySelector('.item');
// console.log(item1.textContent); // "Item 1"
// const container2 = document.getElementById('container2');
// const item2 = container2.querySelector('.item');
// console.log(item2.textContent); // "Item 2"
// // More efficient than document-wide queries
// const form = document.getElementById('myForm');
// const inputs = form.querySelectorAll('input'); // Only in this form
console.log('Scope queries to parent elements for efficiency');
console.log('parent.querySelector only searches within parent');
/**
* EXAMPLE 18: Walking the DOM Tree
*/
console.log('\n--- Example 18: DOM Walking ---');
// Recursive function to walk DOM tree
function walkDOM(node, callback, depth = 0) {
callback(node, depth);
// Only process element children
if (node.children) {
Array.from(node.children).forEach((child) => {
walkDOM(child, callback, depth + 1);
});
}
}
// Usage (in browser):
// walkDOM(document.body, (node, depth) => {
// const indent = ' '.repeat(depth);
// console.log(`${indent}${node.tagName}`);
// });
console.log('Recursive function to traverse entire DOM tree');
console.log('Useful for DOM manipulation or analysis');
/**
* EXAMPLE 19: Performance Best Practices
*/
console.log('\n--- Example 19: Performance ---');
// ❌ Bad: Repeated queries
// for (let i = 0; i < items.length; i++) {
// document.getElementById('container').appendChild(items[i]);
// }
// ✅ Good: Cache reference
// const container = document.getElementById('container');
// for (let i = 0; i < items.length; i++) {
// container.appendChild(items[i]);
// }
// ❌ Bad: Query in loop
// items.forEach(item => {
// const list = document.getElementById('list');
// list.appendChild(item);
// });
// ✅ Good: Query once
// const list = document.getElementById('list');
// items.forEach(item => list.appendChild(item));
// ✅ Best: Use DocumentFragment for batch inserts
// const fragment = document.createDocumentFragment();
// items.forEach(item => fragment.appendChild(item));
// list.appendChild(fragment); // Single reflow
console.log('Cache DOM references');
console.log('Query outside loops');
console.log('Use DocumentFragment for batch operations');
/**
* EXAMPLE 20: Complete DOM Query Utility
*/
console.log('\n--- Example 20: DOM Query Utility ---');
// Utility class for DOM operations
class DOM {
static get(selector, context = document) {
return context.querySelector(selector);
}
static getAll(selector, context = document) {
return Array.from(context.querySelectorAll(selector));
}
static getById(id) {
return document.getElementById(id);
}
static closest(element, selector) {
return element.closest(selector);
}
static parent(element) {
return element.parentElement;
}
static children(element, selector = null) {
if (selector) {
return Array.from(element.children).filter((child) =>
child.matches(selector)
);
}
return Array.from(element.children);
}
static siblings(element) {
return Array.from(element.parentElement.children).filter(
(child) => child !== element
);
}
static hasClass(element, className) {
return element.classList.contains(className);
}
static addClass(element, ...classes) {
element.classList.add(...classes);
return element;
}
static removeClass(element, ...classes) {
element.classList.remove(...classes);
return element;
}
static toggleClass(element, className, force) {
element.classList.toggle(className, force);
return element;
}
static attr(element, name, value) {
if (value === undefined) {
return element.getAttribute(name);
}
element.setAttribute(name, value);
return element;
}
static data(element, key, value) {
if (value === undefined) {
return element.dataset[key];
}
element.dataset[key] = value;
return element;
}
}
// Usage examples:
console.log('DOM utility class methods:');
console.log(" DOM.get('#header')");
console.log(" DOM.getAll('.item')");
console.log(" DOM.closest(element, '.container')");
console.log(" DOM.addClass(element, 'active', 'visible')");
console.log(" DOM.data(element, 'userId')");
console.log('\n========================================');
console.log('DOM Basics Examples Complete');
console.log('Run these in browser console for full effect');
console.log('========================================');