DOM Manipulation - Exercise 1
The DOM (Document Object Model) is a programming interface that represents an HTML document as a tree of objects. It allows JavaScript to access and manipulate the content, structure, and styles of a web page.
// The document object is the entry point to the DOM
console.log(document); // The entire HTML document
// Access the document title
console.log(document.title); // "JavaScript DOM Exercise 1 - Easy | Simply JavaScript"
// Access the body element
console.log(document.body); // The <body> element
The getElementById() method returns the element with the specified ID. It returns null if no element with that ID exists. IDs should be unique in a document.
// HTML: <div id="myBox">Hello World</div>
// Select element by ID
const box = document.getElementById('myBox');
console.log(box); // <div id="myBox">Hello World</div>
console.log(box.id); // "myBox"
// Returns null if ID does not exist
const notFound = document.getElementById('nonExistent');
console.log(notFound); // null
The getElementsByClassName() method returns a live HTMLCollection of all elements with the specified class name. You can access individual elements using index notation.
// HTML: <p class="highlight">First</p>
// <p class="highlight">Second</p>
// <p class="highlight">Third</p>
// Select all elements with class "highlight"
const items = document.getElementsByClassName('highlight');
console.log(items); // HTMLCollection(3) [p.highlight, p.highlight, p.highlight]
console.log(items.length); // 3
console.log(items[0]); // First <p> element
console.log(items[1]); // Second <p> element
The getElementsByTagName() method returns a live HTMLCollection of all elements with the specified tag name. You can use "*" to select all elements.
// HTML: <ul>
// <li>Apple</li>
// <li>Banana</li>
// <li>Cherry</li>
// </ul>
// Select all <li> elements
const listItems = document.getElementsByTagName('li');
console.log(listItems); // HTMLCollection(3) [li, li, li]
console.log(listItems.length); // 3
console.log(listItems[0].textContent); // "Apple"
// Select all elements on the page
const allElements = document.getElementsByTagName('*');
console.log(allElements.length); // Total number of elements
The querySelector() method returns the first element that matches a CSS selector. It returns null if no match is found. You can use any valid CSS selector.
// Select by ID
const box = document.querySelector('#myBox');
// Select by class
const firstHighlight = document.querySelector('.highlight');
// Select by tag
const firstParagraph = document.querySelector('p');
// Select by attribute
const input = document.querySelector('input[type="text"]');
// Select nested element
const listItem = document.querySelector('ul li');
console.log(firstHighlight); // First element with class "highlight"
The querySelectorAll() method returns a static NodeList of all elements that match a CSS selector. Unlike HTMLCollection, this list does not update automatically when the DOM changes.
// Select all elements with class "highlight"
const highlights = document.querySelectorAll('.highlight');
console.log(highlights); // NodeList(3) [p.highlight, p.highlight, p.highlight]
console.log(highlights.length); // 3
// Loop through results with forEach
highlights.forEach(function(element) {
console.log(element.textContent);
});
// Select multiple different selectors
const mixed = document.querySelectorAll('h1, h2, h3');
console.log(mixed.length); // Count of all h1, h2, and h3 elements
The textContent property gets or sets the text content of an element and all its descendants. It returns plain text without any HTML formatting.
// HTML: <p id="message">Hello World</p>
const message = document.getElementById('message');
// Get text content
console.log(message.textContent); // "Hello World"
// Set new text content
message.textContent = 'Welcome to JavaScript!';
console.log(message.textContent); // "Welcome to JavaScript!"
// HTML tags are treated as plain text
message.textContent = '<strong>Bold Text</strong>';
// Displays: <strong>Bold Text</strong> (not bold)
The innerHTML property gets or sets the HTML content inside an element. Unlike textContent, it parses and renders HTML tags. Be careful when using user input with innerHTML to avoid security risks.
// HTML: <div id="container"><p>Original</p></div>
const container = document.getElementById('container');
// Get HTML content
console.log(container.innerHTML); // "<p>Original</p>"
// Set new HTML content
container.innerHTML = '<strong>Bold Text</strong>';
// Now displays: Bold Text (rendered as bold)
// Add multiple elements
container.innerHTML = '<h2>Title</h2><p>Paragraph</p>';
// Clear all content
container.innerHTML = '';
Use getAttribute() to read an attribute value and setAttribute() to set or update an attribute. These methods work with any HTML attribute including custom data attributes.
// HTML: <a id="myLink" href="https://example.com" target="_blank">Click</a>
const link = document.getElementById('myLink');
// Get attribute values
console.log(link.getAttribute('href')); // "https://example.com"
console.log(link.getAttribute('target')); // "_blank"
// Set or update attributes
link.setAttribute('href', 'https://newsite.com');
link.setAttribute('title', 'Visit New Site');
// Add a custom data attribute
link.setAttribute('data-category', 'external');
console.log(link.getAttribute('data-category')); // "external"
The classList.add() method adds one or more CSS classes to an element. If the class already exists, it will not be added again. You can add multiple classes at once.
// HTML: <div id="box" class="container">Box</div>
const box = document.getElementById('box');
// Add a single class
box.classList.add('active');
console.log(box.className); // "container active"
// Add multiple classes at once
box.classList.add('highlight', 'visible', 'rounded');
console.log(box.className); // "container active highlight visible rounded"
// Adding an existing class has no effect
box.classList.add('active');
console.log(box.className); // Still "container active highlight visible rounded"
The classList.remove() method removes one or more CSS classes from an element. If the class does not exist, no error is thrown. You can remove multiple classes at once.
// HTML: <div id="box" class="container active highlight visible">Box</div>
const box = document.getElementById('box');
// Remove a single class
box.classList.remove('active');
console.log(box.className); // "container highlight visible"
// Remove multiple classes at once
box.classList.remove('highlight', 'visible');
console.log(box.className); // "container"
// Removing a non-existent class does nothing
box.classList.remove('nonExistent');
console.log(box.className); // "container"
The classList.contains() method checks if an element has a specific CSS class. It returns true if the class exists and false otherwise. This is useful for conditional logic.
// HTML: <div id="box" class="container active">Box</div>
const box = document.getElementById('box');
// Check if class exists
console.log(box.classList.contains('active')); // true
console.log(box.classList.contains('container')); // true
console.log(box.classList.contains('hidden')); // false
// Use in conditional logic
if (box.classList.contains('active')) {
console.log('The box is active!');
} else {
console.log('The box is not active.');
}
// Toggle based on current state
if (!box.classList.contains('visible')) {
box.classList.add('visible');
}