You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The Document Object Model (DOM) is a programming interface for HTML documents. It represents the page as a tree-like structure where each element, attribute, and text becomes an object that JavaScript can manipulate.
Key Concepts Illustrated
1. Node Types
Document Node: The root of the DOM tree
Element Nodes: HTML tags (div, p, h1, etc.)
Text Nodes: Actual text content
Attribute Nodes: Properties of elements (class, id, src)
Comment Nodes: HTML comments
2. Tree Terminology
Term
Description
Example
Root
Topmost node
document
Parent
Node that contains others
body contains div
Child
Node directly inside another
li inside ul
Siblings
Nodes with same parent
Multiple li elements
Descendant
Any node within another
span inside div
Ancestor
Any node that contains another
html contains all
3. DOM Relationships Properties
// Parent-child relationshipselement.parentNode// Parent nodeelement.childNodes// All child nodeselement.children// Child elements onlyelement.firstChild// First child nodeelement.lastChild// Last child nodeelement.firstElementChild// First child elementelement.lastElementChild// Last child element// Sibling relationshipselement.previousSibling// Previous nodeelement.nextSibling// Next nodeelement.previousElementSibling// Previous elementelement.nextElementSibling// Next element
4. Visualizing DOM Levels
graph TD
subgraph "Level 0 - Document"
D[document]
end
subgraph "Level 1 - Root Element"
D --> H[html]
end
subgraph "Level 2 - Main Sections"
H --> HD[head]
H --> BD[body]
end
subgraph "Level 3 - Containers"
BD --> DV[div .container]
BD --> P[p]
end
subgraph "Level 4 - Content"
DV --> SP[span]
DV --> UL[ul]
P --> TXT[text node]
end
subgraph "Level 5 - Detailed Content"
UL --> LI[li]
LI --> A[a]
A --> LTXT[text node]
end
style D fill:#ef9a9a
style H fill:#f48fb1
style HD fill:#ce93d8
style BD fill:#b39ddb
style DV fill:#9fa8da
style P fill:#80cbc4
style SP fill:#a5d6a7
style UL fill:#c8e6c9
style LI fill:#ffe0b2
style A fill:#ffccbc
style TXT fill:#d7ccc8
style LTXT fill:#d7ccc8
Loading
<!DOCTYPE html><html><head><title>DOM Introduction</title></head><body><h1id="main-title">Hello DOM!</h1><pclass="text">This is a paragraph.</p><divclass="container"><p>Nested paragraph</p></div><script>// DOM is ready!console.log(document);// The entire documentconsole.log(document.body);// Body elementconsole.log(document.head);// Head elementconsole.log(document.title);// Titleconsole.log(document.documentElement);// HTML element</script></body></html>
Key Concepts
Document: The root node of the DOM tree
Elements: HTML tags represented as nodes
Attributes: Properties of elements (class, id, etc.)
Text: Text content within elements
Tree Structure: Parent-child relationships between nodes
<!DOCTYPE html><html><head><title>Content Manipulation</title></head><body><divid="demo"><pid="text-content">Original text</p><divid="html-content"><span>Original HTML</span></div><inputtype="text" id="input-field" value="Input value"></div><divid="output"></div><buttononclick="demonstrateText()">Show textContent</button><buttononclick="demonstrateInnerHTML()">Show innerHTML</button><buttononclick="demonstrateInnerText()">Show innerText</button><buttononclick="modifyContent()">Modify Content</button><script>functiondemonstrateText(){constelement=document.getElementById('text-content');alert('textContent: '+element.textContent);}functiondemonstrateInnerHTML(){constelement=document.getElementById('html-content');alert('innerHTML: '+element.innerHTML);}functiondemonstrateInnerText(){constelement=document.getElementById('text-content');alert('innerText: '+element.innerText);}functionmodifyContent(){// textContent - sets plain textdocument.getElementById('text-content').textContent='Modified with textContent';// innerHTML - sets HTML contentdocument.getElementById('html-content').innerHTML='<strong>Modified with innerHTML</strong>';// value - for input elementsdocument.getElementById('input-field').value='New input value';// Combining text and HTMLconstoutput=document.getElementById('output');output.innerHTML=` <h3>Modified Content:</h3> <p>Text content updated: ${document.getElementById('text-content').textContent}</p> <p>HTML content updated: ${document.getElementById('html-content').innerHTML}</p> `;}// Additional examplesconsole.log('Example of differences:');constdemo=document.getElementById('demo');console.log('innerHTML:',demo.innerHTML);console.log('textContent:',demo.textContent);console.log('innerText:',demo.innerText);</script></body></html>
3.2 Content Properties Comparison
Property
Reads
Writes
Security
innerHTML
HTML content
HTML content
XSS risk
textContent
Raw text
Plain text
Safe
innerText
Rendered text
Plain text
Safe
value
Form field value
Form field value
Safe
Chapter 4: Working with Attributes
4.1 Attribute Manipulation
<!DOCTYPE html><html><head><title>Attribute Manipulation</title><style>
.dynamic-class {
color: blue;
font-weight: bold;
}
.highlight {
background-color: yellow;
}
</style></head><body><h2>Attribute Manipulation Demo</h2><divid="target-element"
class="demo"
data-custom="initial value"
style="padding: 10px; border: 1px solid black;">
This element will have its attributes modified
</div><br><buttononclick="getAttributes()">Get Attributes</button><buttononclick="setAttributes()">Set Attributes</button><buttononclick="removeAttribute()">Remove Attribute</button><buttononclick="toggleClass()">Toggle Class</button><buttononclick="dataAttributes()">Work with Data Attributes</button><divid="output" style="margin-top: 20px;"></div><script>consttarget=document.getElementById('target-element');constoutput=document.getElementById('output');functiongetAttributes(){output.innerHTML='<h3>Current Attributes:</h3>';// Get specific attributeconstclassName=target.getAttribute('class');conststyle=target.getAttribute('style');constdataCustom=target.getAttribute('data-custom');output.innerHTML+=` <p>class: ${className}</p> <p>style: ${style}</p> <p>data-custom: ${dataCustom}</p> <p>has class 'demo': ${target.hasAttribute('class')}</p> <p>has id: ${target.hasAttribute('id')}</p> `;// Get all attributesoutput.innerHTML+='<h4>All attributes:</h4>';Array.from(target.attributes).forEach(attr=>{output.innerHTML+=`<p>${attr.name} = ${attr.value}</p>`;});}functionsetAttributes(){// Set single attributetarget.setAttribute('title','This is a tooltip');// Set multiple attributestarget.setAttribute('data-modified',Date.now());target.setAttribute('aria-label','Modified element');output.innerHTML='<p>Attributes set successfully!</p>';}functionremoveAttribute(){target.removeAttribute('data-custom');output.innerHTML='<p>data-custom attribute removed</p>';}functiontoggleClass(){// Working with classListtarget.classList.toggle('dynamic-class');target.classList.toggle('highlight');output.innerHTML=` <p>Current classes: ${target.className}</p> <p>Contains 'dynamic-class': ${target.classList.contains('dynamic-class')}</p> `;}functiondataAttributes(){// Working with dataset (modern way for data-* attributes)target.dataset.custom='new value';target.dataset.timestamp=Date.now();target.dataset.user='john_doe';output.innerHTML='<h3>Dataset values:</h3>';for(letkeyintarget.dataset){output.innerHTML+=`<p>data-${key}: ${target.dataset[key]}</p>`;}}</script></body></html>
4.2 Attribute Methods
Method
Purpose
getAttribute(name)
Get attribute value
setAttribute(name, value)
Set attribute value
removeAttribute(name)
Remove attribute
hasAttribute(name)
Check if attribute exists
classList.add()
Add class
classList.remove()
Remove class
classList.toggle()
Toggle class
classList.contains()
Check if class exists
Chapter 5: Creating and Removing Elements
5.1 Dynamic Element Creation
<!DOCTYPE html><html><head><title>Creating and Removing Elements</title><style>
.card {
border:1px solid #ddd;
padding:15px;
margin:10px;
border-radius:5px;
box-shadow:02px5pxrgba(0,0,0,0.1);
}
.card-header {
font-weight: bold;
margin-bottom:10px;
}
.card-body {
color:#666;
}
</style></head><body><h2>Dynamic Element Creation</h2><divid="container"></div><buttononclick="createElement()">Create Element</button><buttononclick="createFragment()">Create Fragment</button><buttononclick="cloneElement()">Clone Element</button><buttononclick="removeElement()">Remove Last Element</button><buttononclick="clearContainer()">Clear Container</button><script>constcontainer=document.getElementById('container');letelementCount=0;functioncreateElement(){elementCount++;// Create new elementsconstcard=document.createElement('div');constheader=document.createElement('div');constbody=document.createElement('div');constbutton=document.createElement('button');// Set attributes and contentcard.className='card';card.id=`card-${elementCount}`;header.className='card-header';header.textContent=`Card #${elementCount}`;body.className='card-body';body.textContent=`This card was created at ${newDate().toLocaleTimeString()}`;button.textContent='Click Me';button.onclick=function(){alert(`Card ${elementCount} clicked!`);};// Append elementscard.appendChild(header);card.appendChild(body);card.appendChild(button);// Insert into containercontainer.appendChild(card);}functioncreateFragment(){// DocumentFragment - more efficient for multiple insertionsconstfragment=document.createDocumentFragment();for(leti=0;i<5;i++){elementCount++;constcard=document.createElement('div');card.className='card';card.innerHTML=` <div class="card-header">Batch Card ${elementCount}</div> <div class="card-body">Created with DocumentFragment</div> `;fragment.appendChild(card);}container.appendChild(fragment);}functioncloneElement(){if(container.lastChild){// Clone an existing elementconstoriginal=container.lastChild;constclone=original.cloneNode(true);// true = deep clone// Modify clone to differentiateconstheader=clone.querySelector('.card-header');if(header){header.textContent+=' (Clone)';}container.appendChild(clone);}}functionremoveElement(){if(container.lastChild){container.removeChild(container.lastChild);elementCount--;}}functionclearContainer(){// Remove all childrenwhile(container.firstChild){container.removeChild(container.firstChild);}elementCount=0;}</script></body></html>
<!DOCTYPE html><html><head><title>Dynamic Styling</title><style>
.style-box {
width:200px;
height:200px;
margin:20px;
border:1px solid black;
transition: all 0.3s ease;
}
.custom-class {
border-radius:10px;
box-shadow:04px8pxrgba(0,0,0,0.2);
transform:scale(1.05);
}
</style></head><body><h2>Dynamic Styling Demo</h2><divid="style-demo"><divid="style-box" class="style-box"></div></div><divid="style-controls"><h3>Style Controls:</h3><buttononclick="changeColor()">Change Color</button><buttononclick="toggleClass()">Toggle Class</button><buttononclick="setMultipleStyles()">Multiple Styles</button><buttononclick="getComputedStyles()">Get Computed Styles</button><buttononclick="resetStyles()">Reset</button><br><br><label>Background Color:
<inputtype="color" id="color-picker" onchange="setColor(this.value)"></label><br><br><label>Width:
<inputtype="range" id="width-slider" min="100" max="300" value="200" onchange="setWidth(this.value)"></label></div><divid="style-output"></div><script>constbox=document.getElementById('style-box');constoutput=document.getElementById('style-output');functionchangeColor(){constcolors=['red','blue','green','yellow','purple','orange'];constrandomColor=colors[Math.floor(Math.random()*colors.length)];box.style.backgroundColor=randomColor;output.innerHTML=`<p>Background color set to: ${randomColor}</p>`;}functionsetColor(color){box.style.backgroundColor=color;output.innerHTML=`<p>Background color set to: ${color}</p>`;}functionsetWidth(width){box.style.width=width+'px';output.innerHTML=`<p>Width set to: ${width}px</p>`;}functiontoggleClass(){box.classList.toggle('custom-class');consthasClass=box.classList.contains('custom-class');output.innerHTML=`<p>Custom class ${hasClass ? 'added' : 'removed'}</p>`;}functionsetMultipleStyles(){Object.assign(box.style,{backgroundColor: 'lightblue',border: '3px solid navy',borderRadius: '15px',transform: 'rotate(5deg)',boxShadow: '0 8px 16px rgba(0,0,0,0.3)'});output.innerHTML='<p>Multiple styles applied</p>';}functiongetComputedStyles(){conststyles=window.getComputedStyle(box);output.innerHTML='<h3>Computed Styles:</h3>';constproperties=['backgroundColor','width','height','border','borderRadius','opacity'];properties.forEach(prop=>{output.innerHTML+=`<p>${prop}: ${styles[prop]}</p>`;});}functionresetStyles(){box.style={};box.classList.remove('custom-class');document.getElementById('width-slider').value=200;output.innerHTML='<p>Styles reset to default</p>';}</script></body></html>
8.2 Styling Methods
Method/Property
Description
style.property
Set inline style
classList.add()
Add CSS class
classList.remove()
Remove CSS class
classList.toggle()
Toggle CSS class
className
Get/set all classes
window.getComputedStyle()
Get computed styles
Chapter 9: Advanced DOM Techniques
9.1 Event Delegation and Performance
<!DOCTYPE html><html><head><title>Advanced DOM Techniques</title><style>
.list-item {
padding:10px;
margin:5px;
background-color:#f0f0f0;
cursor: pointer;
transition: background-color 0.3s;
}
.list-item:hover {
background-color:#e0e0e0;
}
.list-item.selected {
background-color:#007bff;
color: white;
}
.performance-metrics {
font-family: monospace;
padding:10px;
background-color:#f5f5f5;
border-radius:5px;
}
</style></head><body><h2>Advanced DOM Techniques</h2><h3>Event Delegation Demo</h3><divid="list-container"><buttononclick="addItems()">Add 1000 Items</button><buttononclick="clearItems()">Clear Items</button><buttononclick="measurePerformance()">Measure Performance</button><divid="item-list"></div></div><divid="output" class="performance-metrics"></div><script>constcontainer=document.getElementById('item-list');constoutput=document.getElementById('output');// Event Delegation - Single event listener for all itemscontainer.addEventListener('click',(e)=>{consttarget=e.target;// Check if clicked element is a list itemif(target.classList.contains('list-item')){// Remove selected class from all itemsdocument.querySelectorAll('.list-item').forEach(item=>{item.classList.remove('selected');});// Add selected class to clicked itemtarget.classList.add('selected');// Get data attributeconstindex=target.dataset.index;output.innerHTML=`<p>Selected item #${index}: ${target.textContent}</p>`;}});functionaddItems(){constfragment=document.createDocumentFragment();conststartTime=performance.now();for(leti=0;i<1000;i++){constitem=document.createElement('div');item.className='list-item';item.dataset.index=i;item.textContent=`Item ${i+1}`;fragment.appendChild(item);}container.appendChild(fragment);constendTime=performance.now();output.innerHTML=`<p>Added 1000 items in ${(endTime-startTime).toFixed(2)}ms</p>`;}functionclearItems(){conststartTime=performance.now();// Efficient clearingwhile(container.firstChild){container.removeChild(container.firstChild);}constendTime=performance.now();output.innerHTML=`<p>Cleared items in ${(endTime-startTime).toFixed(2)}ms</p>`;}functionmeasurePerformance(){constmetrics={totalElements: document.getElementsByTagName('*').length,listItems: document.querySelectorAll('.list-item').length,containerChildren: container.children.length};output.innerHTML='<h3>Performance Metrics:</h3>';for(let[key,value]ofObject.entries(metrics)){output.innerHTML+=`<p>${key}: ${value}</p>`;}}// Debounce function for performancefunctiondebounce(func,wait){lettimeout;returnfunctionexecutedFunction(...args){constlater=()=>{clearTimeout(timeout);func(...args);};clearTimeout(timeout);timeout=setTimeout(later,wait);};}// Throttle function for performancefunctionthrottle(func,limit){letinThrottle;returnfunction(...args){if(!inThrottle){func.apply(this,args);inThrottle=true;setTimeout(()=>inThrottle=false,limit);}};}// Virtual Scrolling Demo (concept)classVirtualScroller{constructor(container,itemHeight,totalItems){this.container=container;this.itemHeight=itemHeight;this.totalItems=totalItems;this.visibleItems=Math.ceil(container.clientHeight/itemHeight);this.scrollTop=0;container.style.overflowY='auto';container.style.height='400px';container.addEventListener('scroll',()=>{this.scrollTop=container.scrollTop;this.render();});this.render();}render(){conststartIndex=Math.floor(this.scrollTop/this.itemHeight);constendIndex=Math.min(startIndex+this.visibleItems+1,this.totalItems);// Only render visible itemsconstfragment=document.createDocumentFragment();for(leti=startIndex;i<endIndex;i++){constitem=document.createElement('div');item.style.height=`${this.itemHeight}px`;item.textContent=`Virtual Item ${i+1}`;item.style.position='absolute';item.style.top=`${i*this.itemHeight}px`;fragment.appendChild(item);}this.container.innerHTML='';this.container.appendChild(fragment);this.container.style.height=`${this.totalItems*this.itemHeight}px`;}}</script></body></html>
The Document Object Model (DOM) is a programming interface for HTML documents. It represents the page as a tree-like structure where each element, attribute, and text becomes an object that JavaScript can manipulate.