The Browser Object Model (BOM) and the Document Object Model (DOM) are fundamental concepts in JavaScript for interacting with web browsers and HTML documents, respectively.
Browser Object Model (BOM)
The BOM provides methods and properties to interact with the browser window itself.
window.open()
This method opens a new browser window or tab. It accepts the following arguments:
url: The URL to load in the new window.name(optional): The name of the new window. Common values include_blank(new tab/window),_self(current window),_parent(parent frame), and_top(topmost frame).specs(optional): A comma-separated string defining window features likewidth=500,height=400.
window.open('https://www.example.com/', '_blank', 'width=500,height=400');
window.close()
Closes the current browser window.
window.close();
window.alert()
Displays a modal dialog box with an alert message.
window.alert('This is an alert message.');
window.confirm()
Dipslays a modal dialog box with a message and 'OK'/'Cancel' buttons, returning true if 'OK' is clicked and false otherwise.
const userConfirmed = window.confirm('Are you sure you want to proceed?');
if (userConfirmed) {
console.log('User confirmed.');
} else {
console.log('User cancelled.');
}
window.prompt()
Displays a modal dialog box with a message and a text input field, returning the user's input string or null if cancelled.
const userName = window.prompt('Please enter your name:', 'Guest');
if (userName !== null) {
console.log(`Hello, ${userName}!`);
}
window.setTimeout()
Executes a function once after a specified delay in milliseconds.
function greet(name) {
console.log(`Hello, ${name}!`);
}
// Execute greet function after 2000ms (2 seconds) with argument 'Alice'
setTimeout(greet, 2000, 'Alice');
window.setInterval()
Executes a function repeatedly at a specified interval in milliseconds.
let counter = 0;
function updateCounter() {
console.log(`Counter: ${counter}`);
counter++;
}
// Execute updateCounter every 1000ms (1 second)
const intervalId = setInterval(updateCounter, 1000);
// To stop the interval later:
// clearInterval(intervalId);
window.location.href
Gets or sets the current page's URL.
console.log(window.location.href);
// To navigate to a new URL:
// window.location.href = 'https://www.example.com/';
Document Object Model (DOM)
The DOM represents the HTML document as a tree of nodes, allowing JavaScript to access and manipulate its content, structure, and style.
Element Selection
document.getElementById(id)
Selects a single element by its unique id attribute.
<p id="unique-paragraph">This is a paragraph.</p>
<script>
const paragraph = document.getElementById('unique-paragraph');
console.log(paragraph);
</script>
document.getElementsByClassName(className)
Selects all elements that have a specific class name, returning an HTMLCollection.
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<script>
const items = document.getElementsByClassName('item');
console.log(items); // HTMLCollection of the two divs
</script>
document.getElementsByTagName(tagName)
Selects all elements with a specific tag name (e.g., 'div', 'p'), returning an HTMLCollection.
<body>
<div>A div element</div>
<p>A paragraph element</p>
<div>Another div element</div>
<script>
const divs = document.getElementsByTagName('div');
console.log(divs);
</script>
</body>
document.querySelector(selector)
Selects the first element that matches a specified CSS selector.
<div class="container">
<p>First paragraph</p>
<p class="highlight">Second paragraph</p>
</div>
<script>
const firstDiv = document.querySelector('div');
console.log(firstDiv);
const highlightedPara = document.querySelector('.container p.highlight');
console.log(highlightedPara);
</script>
document.querySelectorAll(selector)
Selects all elements that match a specified CSS selector, returning a NodeList.
<ul>
<li class="list-item">One</li>
<li class="list-item">Two</li>
<li class="list-item">Three</li>
</ul>
<script>
const listItems = document.querySelectorAll('ul li.list-item');
console.log(listItems); // NodeList of the three list items
</script>
Element Manipulation
element.innerHTML
Gets or sets the HTML content within an element.
<div id="content-box">
<p>Original content</p>
</div>
<script>
const box = document.getElementById('content-box');
// Get HTML content
console.log(box.innerHTML);
// Set HTML content
box.innerHTML = '<h2>New Title</h2><p>Updated content</p>';
</script>
element.textContent
Gets or sets the text content of an element and its descendants, ignoring HTML tags.
<div id="text-container">
<p>Some <strong>bold</strong> text.</p>
</div>
<script>
const container = document.getElementById('text-container');
// Get text content
console.log(container.textContent);
// Output: Some bold text.
// Set text content
container.textContent = 'This is plain text.';
console.log(container.textContent);
// Output: This is plain text.
</script>
element.getAttribute(attributeName)
Retrieves the value of a specified attribute on an element.
<img id="my-image" src="image.jpg" alt="An example image">
<script>
const imgElement = document.getElementById('my-image');
const srcValue = imgElement.getAttribute('src');
console.log(srcValue); // Output: image.jpg
</script>
element.setAttribute(attributeName, value)
Sets or updates the value of a specified attribute on an element.
<div id="target-div">Some content</div>
<script>
const targetDiv = document.getElementById('target-div');
targetDiv.setAttribute('data-custom', 'new-value');
console.log(targetDiv.getAttribute('data-custom')); // Output: new-value
</script>
element.classList
Provides methods to manipulate an element's class list (add, remove, toggle, contains).
<div id="my-element" class="class1 class2">
Content
</div>
<script>
const myElement = document.getElementById('my-element');
// View all classes
console.log(myElement.classList);
// Add a class
myElement.classList.add('class3');
console.log(myElement.classList);
// Remove a class
myElement.classList.remove('class1');
console.log(myElement.classList);
// Toggle a class
myElement.classList.toggle('class2'); // Removes class2
myElement.classList.toggle('class2'); // Adds class2 back
// Check if a class exists
console.log(myElement.classList.contains('class3')); // true
</script>
Element Creation and Insertion
document.createElement(tagName)
Creates a new HTML element node.
const newDiv = document.createElement('div');
newDiv.textContent = 'This is a newly created div.';
element.appendChild(childElement)
Appends a node as the last child of a parent node.
<div id="parent-container">
<p>Existing paragraph.</p>
</div>
<script>
const parent = document.getElementById('parent-container');
const newParagraph = document.createElement('p');
newParagraph.textContent = 'Appended paragraph.';
parent.appendChild(newParagraph);
</script>
element.insertBefore(newElement, referenceElement)
Inserts a node before a specified existing child node.
<div id="parent-container">
<p id="ref-paragraph">Reference paragraph.</p>
</div>
<script>
const parent = document.getElementById('parent-container');
const newParagraph = document.createElement('p');
newParagraph.textContent = 'Inserted paragraph.';
const refParagraph = document.getElementById('ref-paragraph');
parent.insertBefore(newParagraph, refParagraph);
</script>
Element Removal
element.removeChild(childElement)
Removes a child element from its parent.
<div id="container">
<p id="removable-paragraph">This will be removed.</p>
</div>
<script>
const container = document.getElementById('container');
const pToRemove = document.getElementById('removable-paragraph');
container.removeChild(pToRemove);
</script>
element.remove()
Removes the element directly from its parent. This is a more modern and concise way than removeChild.
<div id="container">
<p id="removable-paragraph">This will be removed.</p>
</div>
<script>
const pToRemove = document.getElementById('removable-paragraph');
pToRemove.remove();
</script>
Event Handling
element.addEventListener(event, callback)
Attaches an event listener to an element. The callback function is executed when the specified event occurs.
element: The DOM element to attach the listener to.event: A string specifynig the event type (e.g., 'click', 'mouseover', 'keydown').callback: The function to execute when the event fires.
<button id="my-button">Click Me</button>
<p id="message-area">Status: Idle</p>
<script>
const button = document.getElementById('my-button');
const messageArea = document.getElementById('message-area');
function updateMessage() {
messageArea.textContent = 'Status: Button clicked!';
}
button.addEventListener('click', updateMessage);
</script>
element.removeEventListener(event, callback)
Removes an event listener that was previously attached with addEventListener.
// Assume 'button' and 'updateMessage' are defined as in the previous example.
button.removeEventListener('click', updateMessage);
// Now, clicking the button will no longer call updateMessage.