When you load a web page, the browser creates a Document Object Model (DOM) for that page. The DOM is an object-oriented representation of the HTML elements that make up the page, and it allows you to manipulate those elements using JavaScript.
The DOM is essentially a tree structure, with each HTML element represented as a node in the tree. JavaScript can traverse the tree and manipulate the nodes, changing their content, attributes, styles, and more.
One of the most common uses of the DOM is to manipulate the content of a web page dynamically in response to user actions or other events. For example, you might use JavaScript to change the text of a button when it's clicked, or to show or hide an element when a certain condition is met.
jQuery
jQuery is a popular tool for manipulating the DOM . It is a lightweight JavaScript library that provides a simple and consistent API for common DOM manipulation tasks. It simplifies the process of selecting elements, setting attributes and styles, and handling events.
To use jQuery, you first need to include the jQuery library in your web page by adding the following script tag to the head of your HTML file:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
Once you've included jQuery, you can use it to manipulate the DOM by selecting elements using CSS-like selectors and chaining methods to perform actions on those elements. Here's an example:
// Select all paragraphs with class "my-paragraph"
$('p.my-paragraph')
// Add a new class to the selected elements
.addClass('highlighted')
// Change the text of the selected elements
.text('This paragraph is now highlighted!');
This code selects all paragraphs with the class "my-paragraph", adds a new class called "highlighted", and changes the text of the paragraphs to "This paragraph is now highlighted!".
jQuery also provides a convenient way to handle events. You can use the on() method to attach event handlers to elements selected using jQuery. Here's an example:
// Attach a click event handler to all buttons on the page
$('button').on('click', function() {
// Do something when a button is clicked
alert('Button clicked!');
});
This code attaches a click event handler to all buttons on the page. When a button is clicked, an alert box will pop up with the message "Button clicked!".
In summary, the DOM and jQuery are powerful tools for manipulating web pages dynamically using JavaScript. By understanding how the DOM works and how to use jQuery, you can create rich and interactive web experiences that respond to user actions and events.