
The Browser Object Model (BOM) is a hierarchical representation of the web browser’s window, frames, and other related objects. It provides a way for JavaScript code to interact with the browser, allowing you to access and manipulate various aspects of the user’s browsing experience. At the top of the BOM hierarchy is the window object, which represents the browser window and provides access to other BOM objects, such as the document object. The document object represents the web page currently displayed in the browser and allows you to manipulate the HTML and CSS elements on the page.
- Accessing the Window Object
- Understanding the Document Object Model
- Manipulating HTML Elements with the DOM
- Responding to User Events with Event Handlers
- Working with the History Object
- Using the Location Object to Navigate the Web
- Managing Cookies with the Document Object Model
- Browser Object Model FAQ
Other BOM objects include the history object, which provides access to the browser’s history, the location object, which represents the current URL of the page, and the navigator object, which provides information about the user’s browser and operating system.
Understanding the BOM and how to use it can be incredibly powerful for web developers, as it allows them to create dynamic and interactive web pages. However, it’s important to note that the BOM is not part of the standard JavaScript specification, and therefore, it can differ between browsers. As a result, it’s important to test your code across multiple browsers to ensure cross-compatibility.
In the following sections, we’ll explore the various BOM objects in more detail and show you how to use them to create interactive web pages.
Accessing the Window Object
The window object is the top-level object in the Browser Object Model hierarchy and represents the browser window. It provides access to other BOM objects, as well as the global JavaScript functions and variables.
To access the window object, you can simply use the global “window” variable, which is automatically available in all JavaScript environments. For example, you can use the following code to display the width and height of the browser window:
console.log(window.innerWidth);
console.log(window.innerHeight);
In addition to the innerWidth and innerHeight properties, the window object also provides access to a number of other properties and methods, including:
- document: A reference to the current web page’s document object.
- location: A reference to the current web page’s URL.
- history: A reference to the current web page’s browsing history.
- navigator: Information about the user’s browser and operating system.
- alert(), confirm(), and prompt(): Methods for displaying dialog boxes to the user.
You can also create new windows or tabs using the window object. For example, the following code will open a new window with the specified URL:
window.open("http://www.example.com");
Finally, it’s worth noting that the window object is a global object, meaning that you can access its properties and methods without explicitly referencing it. For example, the following code is equivalent to the code above:
open("http://www.example.com");
In the next section, we’ll explore the document object and show you how to manipulate the HTML elements on a web page.
Understanding the Document Object Model
The Document Object Model (DOM) is a hierarchical representation of the HTML elements on a web page, and it’s a key part of the Browser Object Model. The DOM allows you to access and manipulate HTML elements on a page, including their content, style, and attributes.
To access the DOM, you need to use the document object, which is a property of the window object. The document object provides access to the root of the DOM tree, which is the <html> element. From there, you can traverse the tree to access other elements.
For example, the following code will retrieve the text content of the <h1> element on the page:
var heading = document.querySelector('h1');
console.log(heading.textContent);
The querySelector() method is one of the most common ways to access elements in the DOM. It allows you to select elements using CSS-style selectors. In this case, the selector ‘h1’ selects the first <h1> element on the page.
You can also use other methods, such as getElementById(), getElementsByClassName(), and getElementsByTagName(), to access elements in the DOM.
Once you’ve accessed an element, you can modify its content, style, and attributes. For example, the following code will change the text content of the <h1> element:
heading.textContent = "New heading text";
You can also modify an element’s attributes using the setAttribute() method. For example, the following code will change the href attribute of a link element:
var link = document.querySelector('a');
link.setAttribute('href', 'http://www.example.com');
In addition to accessing and modifying individual elements, you can also create new elements, add them to the DOM, and remove existing elements. These operations allow you to create dynamic and interactive web pages.
In the next section, we’ll explore how to use the DOM to respond to user events and create interactivity on a web page.
Manipulating HTML Elements with the DOM
The Document Object Model (DOM) provides a powerful set of tools for manipulating HTML elements on a web page. In addition to accessing and modifying individual elements, you can create new elements, add them to the DOM, and remove existing elements. This allows you to create dynamic and interactive web pages that respond to user input.
Creating and Appending Elements
To create a new element, you can use the document.createElement() method. This method takes a single argument, which is the name of the element you want to create. For example, the following code will create a new <div> element:
var newDiv = document.createElement('div');
Once you’ve created a new element, you can add it to the DOM using the appendChild() method. For example, the following code will add the new <div> element to the body of the page:
document.body.appendChild(newDiv);
You can also add elements to specific locations in the DOM using methods like insertBefore() and insertAdjacentHTML(). For example, the following code will insert a new <p> element before the first <h1> element on the page:
var newPara = document.createElement('p');
var h1 = document.querySelector('h1');
h1.parentNode.insertBefore(newPara, h1);
Modifying Element Attributes and Content
Once you have a reference to an element, you can modify its attributes and content using properties and methods like innerHTML, textContent, and setAttribute(). For example, the following code will change the text content and background color of a <div> element:
var div = document.querySelector('div');
div.textContent = 'New text content';
div.style.backgroundColor = 'red';
Removing Elements
To remove an element from the DOM, you can use the removeChild() method. This method takes a single argument, which is the element you want to remove. For example, the following code will remove the first <p> element on the page:
var p = document.querySelector('p');
p.parentNode.removeChild(p);
In addition to these basic operations, the DOM provides a wealth of other methods and properties that allow you to manipulate HTML elements in a wide variety of ways. By mastering these tools, you can create web pages that are dynamic, interactive, and responsive to user input.
Responding to User Events with Event Handlers
One of the most powerful features of the Document Object Model (DOM) is its ability to respond to user events, such as clicks, key presses, and mouse movements. By attaching event handlers to HTML elements, you can create interactive web pages that respond to user input in real time.
Attaching Event Handlers
To attach an event handler to an HTML element, you can use the addEventListener() method. This method takes two arguments: the name of the event you want to handle, and a function that will be called when the event occurs. For example, the following code will add a click event handler to a <button> element:
var button = document.querySelector('button');
button.addEventListener('click', function() {
alert('Button clicked!');
});
When the user clicks the button, the function passed to addEventListener() will be called, displaying an alert dialog that says “Button clicked!”.
You can also use the on[event] property to attach event handlers. For example, the following code achieves the same result as the previous example:
var button = document.querySelector('button');
button.onclick = function() {
alert('Button clicked!');
};
This code attaches a click event handler to the button using the onclick property.
Event Object
When an event occurs, the browser creates an event object that contains information about the event, such as the type of event, the target element, and any data associated with the event. You can access this object inside an event handler using the event parameter. For example, the following code will log the target element of a click event to the console:
var button = document.querySelector('button');
button.addEventListener('click', function(event) {
console.log(event.target);
});
This code adds a click event handler to the button that logs the target element to the console when the button is clicked.
Preventing Default Behavior
By default, many HTML elements have built-in behavior that occurs when certain events occur. For example, when the user clicks on a link, the browser navigates to the URL specified in the link’s href attribute. If you want to prevent this default behavior, you can call the preventDefault() method on the event object. For example, the following code will prevent the default behavior of a click event on a link:
var link = document.querySelector('a');
link.addEventListener('click', function(event) {
event.preventDefault();
});
This code adds a click event handler to the link that prevents the default behavior of the click event.
By attaching event handlers to HTML elements, you can create dynamic and interactive web pages that respond to user input in real time. The Document Object Model provides a powerful set of tools for working with events, including the addEventListener() method, the on[event] property, the event object, and the preventDefault() method. By mastering these tools, you can create web pages that are engaging, responsive, and easy to use.
Working with the History Object
The History object is a built-in JavaScript object that represents the user’s browsing history in the current tab. By manipulating the history object, you can control the browser’s back and forward buttons, and navigate between pages in the history.
Accessing the History Object
You can access the History object using the window.history property. This object provides methods and properties for working with the browser history. For example, the following code will log the length of the history to the console:
console.log(window.history.length);
This code accesses the History object through the window.history property and logs the length of the history to the console.
Navigating the History
You can use the History object to navigate through the browsing history. The object provides several methods for this purpose, including:
- back(): This method navigates back one page in the history.
- forward(): This method navigates forward one page in the history.
- go(n): This method navigates to a specific page in the history. The parameter n specifies the number of pages to navigate. A positive value navigates forward in the history, and a negative value navigates back.
For example, the following code will navigate back one page in the history when a button is clicked:
var backButton = document.querySelector('#back-button');
backButton.addEventListener('click', function() {
window.history.back();
});
This code attaches a click event handler to a button with the ID “back-button”. When the button is clicked, the code calls the back() method on the History object to navigate back one page in the history.
Manipulating the History
You can also manipulate the history by adding or modifying entries. The History object provides several methods for this purpose, including:
- pushState(stateObj, title, url): This method adds a new entry to the history. The stateObj parameter is an object that represents the state of the new entry. The title parameter is the title of the new entry, and the url parameter is the URL of the new entry.
- replaceState(stateObj, title, url): This method modifies the current entry in the history. The parameters are the same as for pushState().
For example, the following code will add a new entry to the history when a button is clicked:
var newButton = document.querySelector('#new-button');
newButton.addEventListener('click', function() {
window.history.pushState({page: 'new'}, 'New Page', '/new-page');
});
This code attaches a click event handler to a button with the ID “new-button”. When the button is clicked, the code calls the pushState() method on the History object to add a new entry to the history with the state object {page: ‘new’}, the title “New Page”, and the URL “/new-page”.
The History object provides a powerful set of tools for working with the browser history in JavaScript. By using the methods and properties of this object, you can control the back and forward buttons, navigate through the browsing history, and manipulate the history to create dynamic and interactive web pages.
Using the Location Object to Navigate the Web
The Location object is a built-in JavaScript object that provides information about the current URL of a web page and allows you to navigate to other URLs. By manipulating the Location object, you can change the URL of the current page, reload the page, or navigate to a new page.
Accessing the Location Object
You can access the Location object using the window.location property. This object provides methods and properties for working with the current URL of the page. For example, the following code will log the current URL of the page to the console:
console.log(window.location.href);
This code accesses the Location object through the window.location property and logs the href property, which contains the current URL of the page, to the console.
Changing the URL
You can use the Location object to change the URL of the current page. The object provides several methods for this purpose, including:
- assign(url): This method loads a new document at the specified URL.
- replace(url): This method replaces the current document with a new document at the specified URL.
- reload(): This method reloads the current document.
For example, the following code will navigate to a new page when a button is clicked:
var button = document.querySelector('#navigate-button');
button.addEventListener('click', function() {
window.location.assign('https://www.example.com');
});
This code attaches a click event handler to a button with the ID “navigate-button”. When the button is clicked, the code calls the assign() method on the Location object to load a new document at the URL “https://www.example.com“.
Modifying the URL
You can also modify parts of the URL using the Location object. The object provides several properties for this purpose, including:
- href: This property contains the full URL of the current page.
- protocol: This property contains the protocol (http, https, etc.) of the current page.
- hostname: This property contains the domain name of the current page.
- pathname: This property contains the path and file name of the current page.
- search: This property contains the query string of the current page.
- hash: This property contains the anchor portion of the current page.
For example, the following code will modify the query string of the current URL when a button is clicked:
var button = document.querySelector('#modify-button');
button.addEventListener('click', function() {
window.location.search = '?param=value';
});
This code attaches a click event handler to a button with the ID “modify-button”. When the button is clicked, the code modifies the search property of the Location object to add the query string “?param=value” to the current URL.
The Location object provides a powerful set of tools for working with URLs and navigating the web in JavaScript. By using the methods and properties of this object, you can change the URL of the current page, reload the page, or navigate to a new page, and modify parts of the URL to create dynamic and interactive web pages.
Managing Cookies with the Document Object Model
Cookies are small text files that are stored on a user’s computer by a web server. They can be used to store user preferences, login information, and other data that needs to be persistent between sessions. In JavaScript, you can use the Document Object Model (DOM) to manage cookies and read and write their values.
Creating a Cookie
To create a cookie, you need to set a value for the document.cookie property. The value of the document.cookie property is a semicolon-separated list of name=value pairs. For example, to set a cookie named “username” with the value “johndoe”, you would use the following code:
document.cookie = "username=johndoe";
Note that the cookie value must be URL-encoded if it contains special characters or spaces. You can use the encodeURIComponent() function to encode the value, like this:
document.cookie = "username=" + encodeURIComponent("John Doe");
Reading a Cookie
To read the value of a cookie, you can use the document.cookie property. This property contains all the cookies associated with the current document as a semicolon-separated list of name=value pairs. To get the value of a specific cookie, you need to parse the string and extract the value of the desired cookie. For example, to get the value of the “username” cookie, you would use the following code:
function getCookie(name) {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
if (cookie.indexOf(name + '=') === 0) {
return decodeURIComponent(cookie.substring(name.length + 1));
}
}
return null;
}
var username = getCookie('username');
This code defines a function that parses the document.cookie property to find a cookie with a given name. If the cookie is found, the function returns its value; otherwise, it returns null.
Deleting a Cookie
To delete a cookie, you can set its value to an empty string and set its expiration date to a date in the past. For example, to delete the “username” cookie, you would use the following code:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
This code sets the value of the “username” cookie to an empty string and sets its expiration date to a date in the past, causing the browser to delete the cookie.
In JavaScript, you can use the Document Object Model (DOM) to manage cookies and read and write their values. By setting the document.cookie property, you can create or modify cookies, and by parsing the value of this property, you can read the values of existing cookies. You can also delete cookies by setting their value to an empty string and setting their expiration date to a date in the past. By using these techniques, you can create dynamic and interactive web pages that store user preferences, login information, and other data across sessions.
Browser Object Model FAQ
Q: What is the Browser Object Model?
A: The Browser Object Model (BOM) is a JavaScript interface for interacting with web browser windows and their contents. It provides a way to manipulate the browser’s user interface, as well as access information about the browser and the user’s system.
Q: What objects are included in the Browser Object Model?
A: The BOM includes several objects, such as the window object, the location object, the history object, and the navigator object. These objects allow you to interact with different aspects of the browser and the user’s system.
Q: How can I access the Browser Object Model from JavaScript?
A: The Browser Object Model is built into web browsers and is automatically available in any JavaScript program running in a web page.
Q: What can I do with the window object?
A: The window object represents the current browser window or tab. You can use it to manipulate the browser’s user interface, such as opening or closing windows and dialogs, changing the size and position of windows, and displaying messages to the user.
Q: What is the location object used for?
A: The location object represents the current URL of the web page and provides methods for navigating to other URLs.
Q: How can I manipulate the contents of a web page using the DOM?
A: The Document Object Model (DOM) is a programming interface for HTML and XML documents. It provides a way to access and manipulate the structure and content of a web page using JavaScript.
Q: What is the history object used for?
A: The history object provides a way to navigate back and forth through the user’s browsing history.
Q: How can I set cookies using JavaScript?
A: You can use the Document Object Model (DOM) to set cookies by setting the value of the document.cookie property. Cookies can be used to store user preferences, login information, and other data that needs to be persistent between sessions.
Q: Is the Browser Object Model standardized across different web browsers?
A: The Browser Object Model is not fully standardized across different web browsers, and some browser-specific features may not be available in all browsers. However, the basic functionality of the BOM is supported by most modern web browsers.
- Introduction to the DOM – Web APIs | MDN – Mozilla (developer.mozilla.org)
- How to Use the Browser Object Model – vegibit (vegibit.com)
- Get started viewing and changing the DOM – Microsoft (learn.microsoft.com)
- Browser Object Model – JavaScript Institute (www.javascriptinstitute.org)
- Browser Object Model in JavaScript – W3schools (www.w3schools.in)
- JavaScript Browser Object Model (BOM) – JavaScript (www.javascripttutorial.net)
- html – What’s the difference between the Browser Object (stackoverflow.com)
- JavaScript Browser Object Model (BOM) – YouTube (www.youtube.com)
- Browser Object Model – Wikipedia (en.wikipedia.org)
- The DOM Explained for Beginners – How the (www.freecodecamp.org)
- Browser Object Model (BOM) : MGA – Middle Georgia State (itwebtutorials.mga.edu)
- The Browser Object Model (BOM): Definition & Relation to the DOM (study.com)
- Browser Object Model – javatpoint (www.javatpoint.com)
- Understanding The Browser Object Model in JavaScript (javascript.plainenglish.io)
- Understanding the JavaScript Window Object — SitePoint (www.sitepoint.com)
- Use the Edge browser control on a form – Microsoft Support (support.microsoft.com)
- Accessing the Document Object Model with JavaScript | Linode (www.linode.com)