The DOM (Document Object Model) is an interface that represents the structure of an HTML or XML document as a tree of objects. It allows JavaScript to interact with and manipulate the structure, content, and styling of a web page.
<div>
, <h1>
, etc.) is represented as a node.document.getElementById('elementId'); // Select element by ID document.getElementsByClassName('className'); // Select elements by class document.querySelector('.className'); // Select the first element that matches the CSS selector
Here is a simple example of how DOM manipulation works:
<!DOCTYPE html> <html> <head> <title>DOM Example</title> </head> <body> <h1 id="title">Original Title</h1> <button onclick="changeTitle()">Change Title</button> <script> function changeTitle() { document.getElementById('title').textContent = 'New Title'; } </script> </body> </html>
The BOM (Browser Object Model) represents the browser's environment and is used to interact with the browser outside the scope of the document. It allows JavaScript to access and control browser-specific features, like the window, navigator, screen, and history objects.
window
object is the global object in the browser. All global JavaScript variables and functions are properties of the window
object.alert('Hello, world!'); // Alerts a message to the user console.log(window.innerWidth); // Get the browser window's width console.log(navigator.userAgent); // Get information about the browser console.log(history.back()); // Navigate back in browser history window.location.href = 'https://www.example.com'; // Redirect to another URL
This is an example of using the BOM to redirect users to another page:
<!DOCTYPE html> <html> <head> <title>BOM Example</title> </head> <body> <button onclick="redirect()">Go to Example</button> <script> function redirect() { window.location.href = 'https://www.example.com'; } </script> </body> </html>
Summary:
• DOM focuses on interacting with the document structure (HTML), allowing you to manipulate elements, attributes, styles, and content.
• BOM focuses on interacting with the browser environment, enabling control over things like the browser window, navigation history, screen size, and other browser-related features.
By understanding both DOM and BOM, you can effectively manipulate both the content of the web page and the browser environment using JavaScript.
Published By: Krishanu Jadiya
Updated at: 2024-09-15 01:12:30