Skip to main content

Part 10: Working with APIs in JavaScript

  Working with APIs in JavaScript Outline: 1. Introduction to APIs: 1.1 Definition of APIs: Explanation of what an API (Application Programming Interface) is. Understanding the role of APIs in web development. Types of APIs:  RESTful APIs, SOAP APIs, etc. 1.2 Importance of APIs in Web Development: How APIs facilitate communication between different software systems. Use cases of APIs in modern web development. Examples of popular APIs and their impact. 2. Making API Requests: 2.1 HTTP Methods: Overview of common HTTP methods: GET, POST, PUT, DELETE. Explanation of when to use each HTTP method. 2.2 Fetch API: Introduction to the Fetch API in JavaScript. Making simple GET requests with Fetch. Handling responses from Fetch requests. 2.3 Sending Data in API Requests: Using POST requests to send data to the server. Handling different types of data (JSON, form data) in API requests. 3. Handling API Responses: 3.1 Parsing JSON: Importance of JSON (JavaScript Object Notation) in API responses.

Part 8:What is DOM Manipulation in JavaScript?

What is DOM Manipulation in JavaScript?

What is DOM Manipulation in JavaScript?







Welcome to Part 8 of our JavaScript Step by Step series! In this part, we will find out, what is DOM Manipulation in JavaScript? DOM (Document Object Model) manipulation using JavaScript is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content.

What is the DOM?

The DOM is a tree-like structure that represents the HTML of a web page. Each element in the HTML document is represented as a node in the DOM tree. These nodes are organized in a hierarchical structure, with the document itself at the root and the HTML elements as its branches and leaves.
Here's a simple example of the DOM tree structure for a basic HTML document:
<!DOCTYPE html>
<html>

<head>
        <title>My Web Page</title>
</head>

<body>
        <h1>Hello, World!</h1>
        <p>This is a paragraph.</p>
</body>

</html>
1. The root of the tree is the document object.
2. The <html> element is the parent of the <head> and <body> elements.
3. The <head> and <body> elements are siblings.
4. The <body> element is the parent of the <h1> and <p> elements.
5. The <h1> and <p> elements are siblings.

Why Manipulate the DOM?

Manipulating the DOM is a fundamental part of web development because it allows you to:
1. Change Content: You can update the text, attributes, and structure of a web page in response to user interactions, form submissions, or other events.
2. Change Styles: You can modify the CSS styles of elements to alter their appearance, such as changing colors, sizes, or positions.
3. Respond to Events: You can listen for and react to various events like clicks, keypresses, and mouse movements.
4. Add or Remove Elements: You can dynamically add new elements to the page or remove existing ones.
5. Fetch and Send Data: You can retrieve data from a server (e.g., using AJAX) and update the DOM with the received information.

DOM Manipulation with JavaScript

JavaScript is the primary language for manipulating the DOM. Here are some common tasks you can perform with JavaScript and the DOM:

1. Accessing Elements

You can access DOM elements by their tag name, class name, or ID using methods like document.querySelector() and document.querySelectorAll().
<!DOCTYPE html>
<html>

<head>
        <title>My Web Page</title>
</head>

<body style="background-color: #212121;">
        <h1 style="color: white;">Hello, World!</h1>
        <p id="myElement" style="color: white;">This is a paragraph.</p>
        <script>
                const header = document.querySelector('h1');
                // Selects the first <h1> element
                console.log(header);
                // in browser console: <h1>Hello, World!</h1>
                const paragraphs = document.querySelectorAll('p');
                // Selects all <p> elements
                console.log(paragraphs);
                // Output in browser console: NodeList [p]
                const elementById = document.getElementById('myElement');
                // Selects an element by its ID
                console.log(elementById);

        </script>
</body>
Here is the output in the browser console on right side of the browser window:
Accessing Elements by Tag Name:
You can access elements by their HTML tag names using the document.getElementsByTagName() method. This method returns a collection of elements that match the given tag name. Here's an example:
Suppose you have the following HTML:
<ul>
     <li>Item 1</li>
     <li>Item 2</li>
     <li>Item 3</li>
</ul>
You can access the <li> elements like this:
const listItems = document.getElementsByTagName('li');
// Access the first list item
console.log(listItems[0].textContent); // Output: "Item 1"
Accessing Elements by Class Name:
You can access elements by their CSS class names using the document.getElementsByClassName() method. This method returns a collection of elements with the specified class. Here's an example:
Suppose you have the following HTML:
<p class="highlight">This is a highlighted paragraph.</p>
<p>This is a regular paragraph.</p>
<p class="highlight">Another highlighted paragraph.</p>
You can access the elements with the "highlight" class like this:
const highlightedParagraphs = document.getElementsByClassName('highlight');
// Access the first highlighted paragraph
console.log(highlightedParagraphs[0].textContent);
// Output: "This is a highlighted paragraph."
Accessing Elements by Query Selector:
The document.querySelector() method allows you to access elements using CSS selector syntax. It returns the first element that matches the selector. Here's an example:
Suppose you have the following HTML:
<div class="container">
   <p>This is a paragraph inside a container.</p>
</div>
You can access the <p> element inside the "container" class like this:
const containerParagraph = document.querySelector('.container p');
// Access the paragraph inside the container
console.log(containerParagraph.textContent);
// Output: "This is a paragraph inside a container."
Accessing Elements by Query Selector All:
The document.querySelectorAll() method works similarly to querySelector, but it returns a NodeList containing all elements that match the selector. Here's an example:
Suppose you have the following HTML:
<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>
You can access all the <li> elements like this:
const listItems = document.querySelectorAll('li');
// Access the text content of all list items
listItems.forEach(item => {
    console.log(item.textContent);
});// Output: Item 1    
          // Item 2    
          // Item 3
Accessing Elements by ID:
Accessing elements by their unique ID is done using the document.getElementById() method. It directly retrieves the element with the specified ID. Here's an example:
Suppose you have the following HTML:
<p id="unique-paragraph" style="color: white;">
        This is a unique paragraph.</p>
You can access the paragraph with the "unique-paragraph" ID like this:
const uniqueParagraph = document.getElementById('unique-paragraph');
// Access the unique paragraph
console.log(uniqueParagraph.textContent);
// Output: "This is a unique paragraph."
These are some common methods for accessing elements in the DOM. Depending on your requirements, you can choose the appropriate method to target and manipulate specific elements in your web page.

2. Modifying Content

You can change the text content or HTML content of an element.
header.textContent = 'Hello, New World!';
// Change text content
paragraphs[0].innerHTML = '<em>This is an emphasized paragraph.</em>';
// Change HTML content
Here is the new output:



Modifying content in the Document Object Model (DOM) is a crucial aspect of web development. You can use JavaScript to change the text content and HTML content of elements on a web page. Let's explore this topic in more detail with examples:
Changing Text Content:
You can use the textContent property to change the text content of an HTML element. This property allows you to set or retrieve the text within an element. Here's an example:
Suppose you have the following HTML:
<p id="my-paragraph" style="color: white;">
        This is a paragraph.</p>
You can use JavaScript to change the text content of the paragraph element like this:
// Select the paragraph by its ID
const paragraph = document.getElementById('my-paragraph');
// Change the text content
paragraph.textContent = 'This is the updated paragraph text.';
// Output on browser window will be like this:
// This is the updated paragraph text.
After running this JavaScript code, the text within the paragraph will be updated to "This is the updated paragraph text."
Changing HTML Content:
If you need to change the HTML content of an element, you can use the innerHTML property. This property allows you to set or retrieve the HTML code within an element. Here's an example:
Suppose you have the following HTML:
<div id="my-div">
    <p style="color: white;">This is a paragraph.</p>
</div>
You can use JavaScript to change the HTML content of the <div> element like this:
// Select the div by its ID
const div = document.getElementById('my-div');
// Change the HTML content
div.innerHTML = '<h2 style="color: white;">This is headline in h2 tag.</h2>';
// Output: This is head line in h2 tag.
After running this JavaScript code, the content inside the <div> will be replaced with the new HTML code which will be a h2 tag "This is headline in h2 tag.".
Using textContent vs. innerHTML:
When deciding between textContent and innerHTML, consider the following:
1. Use textContent when you want to change or retrieve plain text content. It's safer because it escapes any HTML tags and prevents potential security issues like cross-site scripting (XSS).
2. Use innerHTML when you need to manipulate or change the structure of an element, including adding or modifying HTML tags.

More Examples

Updating Lists:
Suppose you have an unordered list in HTML:
<ul id="my-list">
                <li>Item 1</li>
                <li>Item 2</li>
                <li>Item 3</li>
        </ul>
        <!--Output . Item 1
                   . Item 2
                   . Item 3-->
You can update the list items with new text using JavaScript like this:
const list = document.getElementById('my-list');
const items = list.querySelectorAll('li');
// Update list items
items[0].textContent = 'Updated Item 1';
items[1].textContent = 'Updated Item 2';
items[2].textContent = 'Updated Item 3';
// Output: . Updated Item 1
//         . Updated Item 2
//         . Updated Item 3
Dynamic Content Generation:
You can also dynamically generate and insert new content using JavaScript. For example, to add a new list item to an existing list replace the above JavaScript code with this one:
const newItem = document.createElement('li');
newItem.textContent = 'New Item';
const list = document.getElementById('my-list');
list.appendChild(newItem);
// Output: . Item 1
//         . Item 2
//         . Item 3
//         . New Item
The above JavaScript code creates a new <li> element with the text "New Item" and appends it to the existing list.
Modifying content in the DOM is a powerful way to create dynamic, interactive web pages that can respond to user input and display up-to-date information.

3. Modifying Styles

Modifying styles using JavaScript is a common practice in web development. It allows you to dynamically change the appearance of HTML elements on a web page. In this section, we'll explore CSS styling in detail with examples in the DOM using JavaScript.
Accessing Element Styles:
Before you can modify an element's styles, you need to access those styles. You can do this using the style property of the element. Here's how you access it:
const element = document.getElementById('my-element');
const styles = element.style;
Now, you can access and modify specific CSS properties of the element through the styles object.
Modifying CSS Properties:
You can modify CSS properties using JavaScript. To change a property, simply assign a new value to it. Here's an example:
Suppose you have the following HTML element:
<h1>Hello, World!</h1>
<em>This is an emphasized paragraph.</em>
You can change the CSS styles of an element like this:
header.style.color = 'blue'; // Change text color
header.style.fontSize = '24px'; // Change font size
Now you will see the output in browser like this:
After running the above JavaScript code, the text within the paragraph will have a blue color and a font size of 24 pixels.
CSS Classes and ClassList:
Instead of directly setting individual CSS properties, you can add or remove CSS classes from elements using the classList property. This is a more flexible and maintainable approach, especially when you want to apply predefined styles. Here's a complete example demonstrating the use of CSS classes and the classList property with HTML, CSS, and JavaScript:
HTML (index.html):
<!DOCTYPE html>
<html lang="en">

<head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="styles.css">
        <title>CSS Classes and ClassList Example</title>
</head>

<body>
        <h1 id="my-heading">CSS Classes Example</h1>
        <p id="my-paragraph">This is a paragraph with a class.</p>
        <button id="toggle-button">Toggle Class</button>
        <script src="script.js"></script>
</body>

</html>
CSS (styles.css):
.my-class {
    color: red;
    font-size: 20px;
}

.highlighted {
    background-color: yellow;
}
JavaScript (script.js):
// Get references to the elements
const paragraph = document.getElementById('my-paragraph');
const button = document.getElementById('toggle-button');

// Add a class to the paragraph
paragraph.classList.add('my-class');
console.log(paragraph);
// <p id="my-paragraph" class="my-class">This is a paragraph with a class.</p>
// Add a click event listener to the button
button.addEventListener('click', function () {
    // Toggle the 'highlighted' class on the paragraph
    paragraph.classList.toggle('highlighted');
    console.log(paragraph);
});
Output in browser:
To see the above example in action, create the three files (index.html, styles.css, and script.js) with the respective code, and then open index.html in a web browser. You can click the "Toggle Class" button to apply or remove the "highlighted" class on the paragraph element.
In the above example, we have an HTML file that references an external CSS file and an external JavaScript file. The HTML file includes a paragraph element with the ID "my-paragraph" and a button with the ID "toggle-button."
The JavaScript code adds the "my-class" to the paragraph element when the page loads. It also adds an event listener to the button. When the button is clicked, it toggles the "highlighted" class on the paragraph element. The "my-class" class sets the text color to red and the font size to 20px, while the "highlighted" class sets the background color to yellow.

4. Adding and Removing Elements

You can create new elements and add them to the DOM, or remove existing elements. Here's a complete example demonstrating how to add and remove HTML elements using JavaScript, along with explanations for each part of the code:
HTML (index.html):
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="styles.css">
  <title>Adding and Removing Elements Example</title>
</head>
<body>
  <h1>Adding and Removing Elements</h1>

  <div id="element-container">
    <!-- Initial content: an empty container -->
  </div>

  <button id="add-button">Add Element</button>
  <button id="remove-button">Remove Element</button>

  <script src="script.js"></script>
</body>
</html>
CSS (styles.css):
/* You can define styles here, but it's not needed for this example. */
JavaScript (script.js):
// Get references to the buttons and the element container
const addButton = document.getElementById('add-button');
const removeButton = document.getElementById('remove-button');
const elementContainer = document.getElementById('element-container');

// Function to add a new element
function addElement() {
    const newElement = document.createElement('div');
    newElement.className = 'added-element';
    newElement.textContent = 'Newly Added Element';

    elementContainer.appendChild(newElement);
    console.log(newElement);
    // <div class="added-element">Newly Added Element</div>
}

// Function to remove the last added element
function removeElement() {
    const addedElements = elementContainer
                            .getElementsByClassName('added-element');
    const lastElement = addedElements[addedElements.length - 1];

    if (lastElement) {
        elementContainer.removeChild(lastElement);
    }
}

// Add a click event listener to the "Add Element" button
addButton.addEventListener('click', addElement);

// Add a click event listener to the "Remove Element" button
removeButton.addEventListener('click', removeElement);
Explanation:
1. In the HTML file, we have a simple structure with a container <div> element (element-container) and two buttons: "Add Element" and "Remove Element."
2. In the CSS file (styles.css), we don't define any styles for this example, but you can include styles if needed.
3. In the JavaScript file (script.js), we start by getting references to the buttons and the element container using document.getElementById().
4. We define two functions: addElement() and removeElement().
. addElement() creates a new <div> element, assigns a class name "added-element," sets its text content, and appends it to the elementContainer.
. removeElement() selects the last element with the class "added-element" and removes it from the elementContainer.
5. We add click event listeners to the "Add Element" and "Remove Element" buttons. When the "Add Element" button is clicked, it calls addElement(), and when the "Remove Element" button is clicked, it calls removeElement().
Now, when you open index.html in a web browser, you can click the "Add Element" button to add new <div> elements with the class "added-element" to the container, and you can click the "Remove Element" button to remove the last added element. This example demonstrates how to dynamically add and remove elements from the DOM using JavaScript.
Output in browser:


5. Insert Before Element

Here's an example demonstrating how to insert elements in different positions using the insertBefore method in JavaScript:
HTML (index.html):
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Inserting Elements Example</title>
</head>

<body>
   <h1>Inserting Elements</h1>

   <ul id="my-list">
         <li>Item 1</li>
         <li>Item 2</li>
    </ul>

  <button id="insert-before-button">Insert New Item Before Item 1</button>
  <button id="insert-after-button">Insert New Item After Item 1</button>
  <button id="insert-first-button">
                Insert New Item as the First Item</button>
  <button id="insert-last-button">
                Insert New Item as the Last Item</button>

   <script src="script.js"></script>
</body>

</html>
JavaScript (script.js):
// Get references to the buttons and the list
const insertBeforeButton = document.getElementById('insert-before-button');
const insertAfterButton = document.getElementById('insert-after-button');
const insertFirstButton = document.getElementById('insert-first-button');
const insertLastButton = document.getElementById('insert-last-button');
const myList = document.getElementById('my-list');

// Function to insert an item before a specific element
function insertBeforeItem() {
    // Create a new list item
    const newItem = document.createElement('li');
    newItem.textContent = 'New Item';

    // Get the reference to the existing item (Item 3)
    const referenceItem = myList.querySelector('li:nth-child(1)');
    // Select the first li element
    console.log(referenceItem);

    // Insert the new item before the reference item
    myList.insertBefore(newItem, referenceItem);
}

// Function to insert an item after a specific element
function insertAfterItem() {
    // Create a new list item
    const newItem = document.createElement('li');
    newItem.textContent = 'New Item';

    // Get the reference to the existing item (Item 2)
    const referenceItem = myList.querySelector('li:nth-child(2)');

    // Insert the new item after the reference item
    referenceItem.parentElement
        .insertBefore(newItem, referenceItem.nextElementSibling);
}

// Function to insert an item as the first child
function insertAsFirstItem() {
    // Create a new list item
    const newItem = document.createElement('li');
    newItem.textContent = 'New Item';

    // Insert the new item as the first child of the list
    myList.insertBefore(newItem, myList.firstElementChild);
}

// Function to insert an item as the last child
function insertAsLastItem() {
    // Create a new list item
    const newItem = document.createElement('li');
    newItem.textContent = 'New Item';

    // Insert the new item as the last child of the list
    myList.appendChild(newItem);
}

// Add click event listeners to the buttons
insertBeforeButton.addEventListener('click', insertBeforeItem);
insertAfterButton.addEventListener('click', insertAfterItem);
insertFirstButton.addEventListener('click', insertAsFirstItem);
insertLastButton.addEventListener('click', insertAsLastItem);
Output before clicking buttons:




Output after clicking buttons:

Here is another example:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Inserting Elements Example</title>
</head>

<body>
     <h1>Inserting Elements</h1>

     <ul id="my-list">
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
      </ul>

      <button id="before-parent">Befor Parent</button>
      <button id="after-parent">After Parent</button>
      <button id="before-first-element-child">Befor First Child</button>
      <button id="after-first-element-child">After First Child</button>
      <button id="after-next-element-sibling">After Next Child</button>

      <script src="script.js"></script>
</body>

</html>
JavaScript (script.js):
// Get references to the buttons and the list
const beforParentBtn = document.getElementById('before-parent');
const afterParentBtn = document.getElementById('after-parent');
const beforeChildBtn = document
                       .getElementById('before-first-element-child');
const afterChildBtn = document
                       .getElementById('after-first-element-child');
const afterNextChildBtn = document
                       .getElementById('after-next-element-sibling');

// Function to new heading before parent
function beforeParent() {
    const myList = document.getElementById('my-list');
    let parent = document.body;
    // Create a new list item
    const newItem = document.createElement('h2');
    newItem.textContent = 'New Heading';
    // Insert the new item before the reference item
    parent.insertBefore(newItem, myList);
    beforParentBtn.disabled = true;
}

// Function to inserte new item after parent
function afterParent() {
    // Create a new list item
    const myList = document.getElementById('my-list');
    const newItem = document.createElement('li');
    newItem.textContent = 'New Item';

    // Get the positon where new item to be inserted
    const pos = myList.firstElementChild;
    console.log(pos);

    // Insert the new item before the reference item
    myList.insertBefore(newItem, pos);
    afterParentBtn.disabled = true;
}

// Function to inserte before first child
function beforeChild() {
    const myList = document.getElementById('my-list');
    // Create a new list item
    const newItem = document.createElement('li');
    newItem.textContent = 'New Item';

    // Get the positon where new item to be inserted
    let pos = myList.firstElementChild;
    pos = pos.nextElementSibling.nextElementSibling;
    console.log(pos);

    // Insert the new item before the reference item
    myList.insertBefore(newItem, pos);
    beforeChildBtn.disabled = true;
}
// Function to inserte before first child
function afterChild() {
    const myList = document.getElementById('my-list');
    // Create a new list item
    const newItem = document.createElement('li');
    newItem.textContent = 'New Item';

    // Get the positon where new item to be inserted
    let pos = myList.firstElementChild;
    pos = pos.nextElementSibling.nextElementSibling;
    pos = pos.nextElementSibling.nextElementSibling;
    console.log(pos);

    // Insert the new item before the reference item
    myList.insertBefore(newItem, pos);
    afterChildBtn.disabled = true;
}
// Function to inserte before first child
function afterNextChild() {
    const myList = document.getElementById('my-list');
    // Create a new list item
    const newItem = document.createElement('li');
    newItem.textContent = 'New Item';

    // Get the positon where new item to be inserted
    let pos = myList.firstElementChild;
    pos = pos.nextElementSibling.nextElementSibling;
    pos = pos.nextElementSibling.nextElementSibling;
    pos = pos.nextElementSibling.nextElementSibling;
    console.log(pos);

    // Insert the new item before the reference item
    myList.insertBefore(newItem, pos);
    afterNextChildBtn.disabled = true;
}

// Add click event listeners to the buttons
beforParentBtn.addEventListener('click', beforeParent);
// Add click event listeners to the set position button
afterParentBtn.addEventListener('click', afterParent);
// Add click event listeners to before child button
beforeChildBtn.addEventListener('click', beforeChild);
// Add click event listeners to after child button
afterChildBtn.addEventListener('click', afterChild);
// Add click event listeners to after next child button
afterNextChildBtn.addEventListener('click', afterNextChild);
Output in browser:




In the above example, we have added five buttons: "Before Parent", "After Parent", "Before First Child", "After First Child" and "After Next Child". Each button triggers a different method to insert "New Item" at various positions using insertBefore.
This demonstrates how you can use different techniques to insert elements at specific positions in the DOM.

Manipulating Inline Styles

To manipulate inline styles using JavaScript, you can use the style property of a DOM element. This property allows you to get or set inline styles for an element. Here's an example:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manipulating Inline Styles</title>
    <style>
          /* Define a CSS style for demonstration */
          .highlighted {
                background-color: yellow;
          }
    </style>
</head>

<body>
        <h1 id="my-heading">Hello, Inline Styles!</h1>
        <button id="highlight-button">Highlight</button>
        <button id="reset-button">Reset</button>

        <script>
              // Get references to the elements
              const heading = document.getElementById('my-heading');
              const highlightButton = document
                                    .getElementById('highlight-button');
              const resetButton = document.getElementById('reset-button');

              // Function to add a style to the heading
              function addStyle() {
                     heading.style.backgroundColor = 'yellow';
              }

                // Function to reset the style of the heading
                function resetStyle() {
                        heading.style.backgroundColor = '';
                }

                // Add click event listeners to the buttons
                highlightButton.addEventListener('click', addStyle);
                resetButton.addEventListener('click', resetStyle);
        </script>
</body>

</html>
In the above example:
1. We have an HTML document with a heading element and two buttons. We also define a CSS style for the class "highlighted" to be used in the demonstration.
2. In the JavaScript section, we get references to the heading element and the buttons using getElementById.
3. We define two functions:
. addStyle(): This function sets the backgroundColor style property of the heading element to "yellow" when the "Highlight" button is clicked.
. resetStyle(): This function resets the backgroundColor style property of the heading element to an empty string when the "Reset" button is clicked.
4. We add click event listeners to the buttons, which call the respective functions when clicked.
When you click the "Highlight" button, it adds the inline style to change the background color of the heading to yellow, making it highlighted. Clicking the "Reset" button removes the inline style, returning the heading to its original appearance.
This example demonstrates how to manipulate inline styles of elements using JavaScript.

Get Computed Styles

Computed styles are used in JavaScript for various purposes, including:
1. Inspecting Element Styles: Computed styles allow you to inspect the actual styles applied to an element after considering inheritance, styles from CSS rules, and any applied inline styles. This is valuable for debugging and understanding how styles are affecting an element's appearance.
2. Dynamic Styling: You can use computed styles to check the current styles of an element and make dynamic adjustments or modifications based on these styles. For example, you can change the color of text when it reaches a certain size or apply styles conditionally based on user interactions.
3. Responsive Web Design: In responsive web design, you can use computed styles to adapt the layout and styling of elements based on the available screen size, making your web pages more flexible and user-friendly on different devices.
4. User Interface Interactions: When creating interactive elements like buttons, you can use computed styles to provide visual feedback to users. For example, you might change the background color of a button when it's hovered over or clicked.
5. Animation and Transition Control: Computed styles are useful for controlling CSS transitions and animations in JavaScript. You can read the current styles and then apply changes to trigger animations or transitions smoothly.
6. Validation and Error Handling: You can use computed styles to check if certain styles are applied as expected. This can be especially helpful in form validation or error handling scenarios.
7. Accessibility: Computed styles can help improve accessibility by allowing you to check and modify the visual presentation of elements to ensure they meet accessibility standards. For example, you can adjust text size, contrast, or color schemes.
8. Cross-Browser Compatibility: Computed styles provide a consistent way to access styles across different browsers, ensuring your JavaScript code behaves the same way in various environments.
In summary, computed styles are a valuable tool in JavaScript for working with the visual presentation of web elements and for creating dynamic, responsive, and user-friendly web applications. They enable you to read and manipulate the styling of elements to achieve a wide range of effects and interactions.
To get computed styles of an element using JavaScript, you can use the getComputedStyle method. This method allows you to retrieve the computed values of CSS properties applied to an element. Here's an example:
<!DOCTYPE html>
<html lang="en">

<head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width,
                    initial-scale=1.0">
        <title>Get Computed Styles</title>
        <style>
                /* Define a CSS style for demonstration */
                .highlighted {
                        background-color: yellow;
                        color: blue;
                        font-size: 20px;
                }
        </style>
</head>

<body>
        <div id="my-div">Hello, Get Computed Styles!</div>
        <button id="get-styles-button">Get Computed Styles</button>

        <script>
                // Get references to the elements
                const myDiv = document.getElementById('my-div');
                const getStylesButton = document
                                    .getElementById('get-styles-button');
                // Function to get and display computed styles
                function getAndDisplayStyles() {
                     // Get the computed styles of the element
                     const computedStyles = getComputedStyle(myDiv);
                     // Extract and display some computed properties
                     const backgroundColor =
                                        computedStyles.backgroundColor;
                     const color = computedStyles.color;
                     const fontSize = computedStyles.fontSize;
                     console.log('Computed Background Color:',
                                                        backgroundColor);
                    // Output: Computed Background Color: rgba(0, 0, 0, 0)
                     console.log('Computed Text Color:', color);
                    // Output: Computed Text Color: rgb(0, 0, 0)
                     console.log('Computed Font Size:', fontSize);
                    // Output: Computed Font Size: 16px
                }
           // Add click event listener to the button
          getStylesButton.addEventListener('click', getAndDisplayStyles);
        </script>
</body>
</html>
In the above example:
1. We have an HTML document with a div element and a button. We also define a CSS style for the class "highlighted" to be used in the demonstration.
2. In the JavaScript section, we get references to the div element and the button using getElementById.
3. We define a function called getAndDisplayStyles(). Inside this function:
    We use the getComputedStyle method to get the computed styles of the myDiv element.
    We extract and display some computed properties, such as backgroundColor, color, and fontSize.
4. We add a click event listener to the button. When clicked, it calls the getAndDisplayStyles() function, which retrieves and displays the computed styles of the myDiv element.
When you click the "Get Computed Styles" button, it will log the computed background color, text color, and font size of the myDiv element to the console. This demonstrates how to use the getComputedStyle method to retrieve computed styles in JavaScript.

Transition and Animation

To create transitions and animations in HTML and CSS, you can use the transition and @keyframes properties. Here's a working example of both transition and animation:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Transition and Animation Example</title>
    <style>
          /* Define the CSS for the element with transition */
          .box {
                   width: 100px;
                   height: 100px;
                   background-color: red;
                   transition: width 1s, height 1s, background-color 1s;
                }

                /* Define the CSS for the element with animation */
                .animated-box {
                        width: 100px;
                        height: 100px;
                        background-color: blue;
                        animation: bounce 2s infinite;
                }

                /* Define the animation keyframes */
                @keyframes bounce {

                        0%,
                        100% {
                                transform: translateY(0);
                        }

                        50% {
                                transform: translateY(-50px);
                        }
                }

                /* Style the buttons */
                button {
                        margin: 10px;
                        padding: 5px 10px;
                        font-size: 16px;
                }
        </style>
</head>

<body>
        <div class="box" id="transition-box"></div>
        <div class="animated-box"></div>

        <button id="transition-button">Toggle Transition</button>
        <button id="animation-button">Toggle Animation</button>

 <script>
   // Get references to the elements and buttons
   const transitionBox = document.getElementById('transition-box');
   const transitionButton = document.getElementById('transition-button');
   const animatedBox = document.querySelector('.animated-box');
   const animationButton = document.getElementById('animation-button');

                // Function to toggle transition
                function toggleTransition() {
                        transitionBox.classList.toggle('box');
                }

                // Function to toggle animation
                function toggleAnimation() {
                        animatedBox.classList.toggle('animated-box');
                }

   // Add click event listeners to the buttons
   transitionButton.addEventListener('click', toggleTransition);
   animationButton.addEventListener('click', toggleAnimation);
 </script>
</body>
</html>
In this example:
1. We have an HTML document with two elements. One has a transition applied, and the other has an animation applied. There are also two buttons to toggle the transition and animation.
2. In the CSS section, we define the styles for the transition element (class "box") and the animated element (class "animated-box"). We specify a transition property for the transition, and we define an animation called "bounce" using @keyframes for the animated element.
3. When you click the "Toggle Transition" button, it toggles the "box" class on the transition element. This triggers a transition effect on the element's width, height, and background color.
4. When you click the "Toggle Animation" button, it toggles the "animated-box" class on the animated element. This triggers an animation where the element bounces up and down.
You can experiment with this example to see how transitions and animations work in response to button clicks. Transitions create smooth property changes over a specified duration, while animations allow you to create custom, keyframe-based animations.
Outp in browser:


DOM events in JavaScript

In the context of JavaScript and web development, DOM events refer to interactions and occurrences that take place within the Document Object Model (DOM) of a web page. These events are generated by user actions, the browser, or other sources and can be detected and handled by JavaScript code. DOM events are a fundamental part of creating interactive web applications.
There are numerous types of events in JavaScript, but some of the most commonly used events include:
1. Mouse Events:
click: Occurs when a mouse click is detected.
mouseover and mouseout: Triggered when the mouse pointer enters or leaves an element.
mousedown and mouseup: Fired when a mouse button is pressed down or released.
mousemove: Occurs when the mouse pointer moves over an element.
2. Keyboard Events:
keydown and keyup: Triggered when a key on the keyboard is pressed or released.
keypress: Occurs when a character key is pressed.
3. Form Events:
submit: Fired when a form is submitted.
input, change, and focus: Events related to form input elements.
4. Document Loading Events:
load: Occurs when a web page and its resources (e.g., images) have finished loading.
DOMContentLoaded: Fired when the initial HTML document has been completely loaded and parsed.
5. Window Events:
resize: Occurs when the browser window is resized.
scroll: Triggered when the user scrolls a page.
beforeunload: Fired when a user attempts to leave a page, typically prompting a confirmation dialog.
6. Touch Events:
touchstart, touchmove, and touchend: Events related to touch input on touchscreen devices.
7. Custom Events:
Developers can create custom events to trigger specific actions within their applications.
8. Drag and Drop Events:
Events related to dragging and dropping elements on a web page.
9. Media Events:
Events associated with audio and video elements, such as play, pause, and ended.
10. Network Events:
Events related to network requests, like load, error, and readystatechange.
These are just a few examples of commonly used DOM events in JavaScript. Event handling is essential for creating interactive and responsive web applications. You can attach event listeners to DOM elements to respond to user actions and control the behavior of your web page.

1. Mouse Events:

Here's a working example that demonstrates various mouse events in JavaScript, including click, mouseover, mouseout, mousedown, mouseup, and mousemove:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mouse Events Example</title>
    <style>
            /* Style the element */
            #target-element {
                    width: 100px;
                    height: 100px;
                    background-color: blue;
                    color: white;
                    text-align: center;
                    line-height: 100px;
                }
    </style>
</head>

<body>
        <div id="target-element">Hover Me</div>

        <script>
          // Get a reference to the target element
          const targetElement = document.getElementById('target-element');

          // Function to handle the 'click' event
          function handleClick() {
                  targetElement.innerHTML = 'Clicked!';
          }

         // Function to handle the 'mouseover' event
          function handleMouseOver() {
                  targetElement.style.backgroundColor = 'red';
          }

          // Function to handle the 'mouseout' event
          function handleMouseOut() {
                   targetElement.style.backgroundColor = 'blue';
          }

         // Function to handle the 'mousedown' event
          function handleMouseDown() {
                  targetElement.style.backgroundColor = 'green';
          }

          // Function to handle the 'mouseup' event
          function handleMouseUp() {
                 targetElement.style.backgroundColor = 'red';
          }

          // Function to handle the 'mousemove' event
          function handleMouseMove() {
                 targetElement.innerHTML = 'Mouse Moving';
           }

          // Add event listeners to the target element
          targetElement.addEventListener('click', handleClick);
          targetElement.addEventListener('mouseover', handleMouseOver);
          targetElement.addEventListener('mouseout', handleMouseOut);
          targetElement.addEventListener('mousedown', handleMouseDown);
          targetElement.addEventListener('mouseup', handleMouseUp);
          targetElement.addEventListener('mousemove', handleMouseMove);
    </script>
</body>
</html>
In the above example:
1. We have an HTML document with a <div> element with the ID "target-element." This element will be the target for the mouse events.
2. In the JavaScript section, we define several event handler functions:
handleClick(): Called when the element is clicked.
handleMouseOver(): Called when the mouse pointer enters the element.
handleMouseOut(): Called when the mouse pointer leaves the element.
handleMouseDown(): Called when a mouse button is pressed while over the element.
handleMouseUp(): Called when a mouse button is released while over the element.
handleMouseMove(): Called when the mouse pointer moves over the element.
3. We add event listeners to the "target-element" for each of the defined mouse events. When the events occur, the corresponding event handlers are invoked.
When you interact with the "target-element" by clicking, hovering over, moving the mouse, or pressing and releasing the mouse button, you'll see how the event handlers modify the element's appearance and content, demonstrating the different mouse events in action.

2. Keyboard Events:

Here's a working example that demonstrates keyboard events in JavaScript, including keydown, keyup, and keypress:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Keyboard Events Example</title>
    <style>
            /* Style the element */
            #output {
                  background-color: lightgray;
                  padding: 10px;
          }
  </style>
</head>

<body>
        <div id="output">Press a key</div>

        <script>
                // Get a reference to the output element
                const output = document.getElementById('output');

                // Function to handle the 'keydown' event
                function handleKeyDown(event) {
                        output.innerHTML = `Key Down: ${event.key}
                                            (Key Code: ${event.keyCode})`;
                        output.style.backgroundColor = 'lightblue';
                }

                // Function to handle the 'keyup' event
                function handleKeyUp(event) {
                        output.innerHTML = `Key Up: ${event.key}
                                            (Key Code: ${event.keyCode})`;
                        output.style.backgroundColor = 'lightgreen';
                }

                // Function to handle the 'keypress' event
                function handleKeyPress(event) {
                        output.innerHTML = `Key Pressed: ${event.key}
                                            (Key Code: ${event.keyCode})`;
                        output.style.backgroundColor = 'lightpink';
                }

                // Add event listeners to the document
                document.addEventListener('keydown', handleKeyDown);
                document.addEventListener('keyup', handleKeyUp);
                document.addEventListener('keypress', handleKeyPress);
        </script>
</body>

</html>
In the above example:
1. We have an HTML document with a <div> element with the ID "output." This element will display information about keyboard events.
2. In the JavaScript section, we define three event handler functions:
handleKeyDown(event): Called when a key is pressed down.
handleKeyUp(event): Called when a key is released.
handleKeyPress(event): Called when a character key is pressed.
3. We add event listeners to the document object for each of the keyboard events: keydown, keyup, and keypress. When these events occur, the corresponding event handlers are invoked.
4. The event handlers update the "output" element to display information about the key and its key code. They also change the background color to differentiate between the different types of events.
When you press keys on your keyboard, you'll see how the event handlers respond to keydown, keyup, and keypress events, displaying information about the key and key code in the "output" element and changing the background color to indicate the type of event.

3. Form Events:

Here's a working example that demonstrates form events in JavaScript, including submit, input, change, and focus:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form Events Example</title>
    <style>
           /* Style the form */
          form {
                  padding: 10px;
                  border: 2px solid lightgray;
                  width: 300px;
                  margin: 20px auto;
          }

        p {
                  text-align: center;
          }
    </style>
</head>

<body>
        <form id="my-form">
                <label for="name">Name:</label>
                <input type="text" id="name" required>
                <br><br>
                <label for="email">Email:</label>
                <input type="email" id="email" required>
                <br><br>
                <button type="submit">Submit</button>
        </form>

        <p id="output">Output</p>

        <script>
                // Get a reference to the form and output element
                const form = document.getElementById('my-form');
                const output = document.getElementById('output');

                // Function to handle the 'submit' event
                function handleSubmit(event) {                        
                        // Prevent the form from actually submitting
                        event.preventDefault();
                        output.textContent = 'Form Submitted!';
                }

                // Function to handle the 'input' event
                function handleInput() {
                        output.textContent = 'Input Changed';
                }

                // Function to handle the 'change' event
                function handleChange() {
                        output.textContent = 'Value Changed';
                }

                // Function to handle the 'focus' event
                function handleFocus() {
                        output.textContent = 'Input Focused';
                }

                // Add event listeners to the form and input elements
                form.addEventListener('submit', handleSubmit);
                form.addEventListener('input', handleInput);
                form.addEventListener('change', handleChange);

                // Add a focus event listener to each input element
                const nameInput = document.getElementById('name');
                const emailInput = document.getElementById('email');
                nameInput.addEventListener('focus', handleFocus);
                emailInput.addEventListener('focus', handleFocus);
        </script>
</body>
</html>
In the above example:
1. We have an HTML document with a form that includes two input fields (Name and Email) and a submit button. We also have a <p> element with the ID "output" where messages will be displayed.
2. In the JavaScript section, we define four event handler functions:
handleSubmit(event): Called when the form is submitted. It prevents the form from actually submitting by using event.preventDefault() and displays a "Form Submitted!" message.
handleInput(): Called when the input value changes. It displays an "Input Changed" message.
handleChange(): Called when the input value changes (similar to input but specific to certain input types). It displays a "Value Changed" message.
handleFocus(): Called when an input field receives focus. It displays an "Input Focused" message.
3. We add event listeners to the form for the submit, input, and change events. We also add focus event listeners to each input element individually.
The event handlers update the "output" element to display different messages based on the form events.
When you interact with the form by entering data, changing input values, or submitting the form, you'll see how the event handlers respond to submit, input, change, and focus events, displaying corresponding messages in the "output" element.

4. Document Loading Events:

Here's a working example that demonstrates document loading events in JavaScript, including load and DOMContentLoaded:
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document Loading Events Example</title>
   <style>
           /* Style the container */
           .container {
                        text-align: center;
                        margin: 50px auto;
                        padding: 20px;
                        border: 2px solid lightgray;
                        width: 300px;
           }
   </style>
</head>

<body>
        <div class="container" id="content">
                <p>Loading...</p>
        </div>

        <script>
                // Function to handle the 'load' event
                function handleLoad() {
                    setTimeout(function () {
                       const content = document.getElementById('content');
                       content.innerHTML = 'Page Loaded!';
                    }, 3000); // Simulate a 2-second delay
                }

                // Function to handle the 'DOMContentLoaded' event
                function handleDOMContentLoaded() {
                    setTimeout(function () {
                       const content = document.getElementById('content');
                       content.innerHTML = 'DOM Content Loaded!';
                    }, 2000); // Simulate a 1-second delay
                }

    // Add event listeners to the window
    window.addEventListener('load', handleLoad);
    document.addEventListener('DOMContentLoaded', handleDOMContentLoaded);
    </script>
</body>
</html>
In the above example:
1. We have an HTML document with a <div> element with the class "container" and the ID "content." Initially, it contains a loading message.
2. In the JavaScript section, we define two event handler functions:
handleLoad(): Called when the entire page, including its resources like images and styles, has finished loading. It updates the content of the "content" element to display "Page Loaded!"
handleDOMContentLoaded(): Called when the initial HTML document has been completely loaded and parsed. It updates the content of the "content" element to display "DOM Content Loaded!"
3. We add event listeners to the window for the load event and to the document for the DOMContentLoaded event.
4. The event handlers update the "content" element to display different messages based on the document loading events.
5. In the handleLoad() and handleDOMContentLoaded functions, setTimeout is used to introduce delays. The "Page Loaded!" message will appear after a 3-second delay, and the "DOM Content Loaded!" message will appear after a 2-second delay. These delays make it easier to observe the sequence of loading events. You can adjust the delay times to suit your preference.
When you open this HTML page, you'll see different messages displayed in the "content" element. The "Loading..." message will be replaced by "DOM Content Loaded!" when the document's initial HTML has been parsed, and it will be further replaced by "Page Loaded!" when all page resources have finished loading.

5. Window Events:

Here's a working example that demonstrates window events in JavaScript, including resize, scroll, and beforeunload:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Window Events Example</title>
    <style>
                /* Style the container */
                .container {
                        text-align: center;
                        margin: 50px auto;
                        padding: 20px;
                        border: 2px solid lightgray;
                        width: 300px;
                }
    </style>
</head>

<body>
        <div class="container" id="content">
                <p>Window Events</p>
        </div>

        <script>
                // Function to handle the 'resize' event
                function handleResize() {
                       const content = document.getElementById('content');
                       content.innerHTML = 'Window Resized';
                }

                // Function to handle the 'scroll' event
                function handleScroll() {
                       const content = document.getElementById('content');
                       content.innerHTML = 'Window Scrolled';
                }

                // Function to handle the 'beforeunload' event
                function handleBeforeUnload(event) {
                 // Display a confirmation message
                 event.returnValue = 'Changes you made may not be saved.';
                }

            // Add event listeners to the window
            window.addEventListener('resize', handleResize);
             window.addEventListener('scroll', handleScroll);
             window.addEventListener('beforeunload', handleBeforeUnload);
        </script>
</body>

</html>
In the above example:
1. We have an HTML document with a <div> element with the class "container" and the ID "content." Initially, it contains a message related to window events.
2. In the JavaScript section, we define three event handler functions:
handleResize(): Called when the window is resized. It updates the content of the "content" element to display "Window Resized."
handleScroll(): Called when the window is scrolled. It updates the content of the "content" element to display "Window Scrolled."
handleBeforeUnload(event): Called before the user navigates away from the page. It displays a confirmation message asking if the user wants to leave the page without saving changes.
3. We add event listeners to the window for the resize, scroll, and beforeunload events.
4. The event handlers update the "content" element to display different messages based on the window events. The beforeunload event handler displays a confirmation message when the user tries to leave the page.
You can test these events by resizing the browser window, scrolling the page, and attempting to close the page, which will trigger the corresponding event handlers and display the associated messages.

Event Bubbling and Event Capturing

Event bubbling and event capturing are two phases of the event propagation process in the DOM (Document Object Model) when an event occurs on an element. These phases determine the order in which event handlers are executed on the DOM tree.
Event Bubbling: 
In event bubbling, when an event is triggered on a target element, it starts from the target element and bubbles up the DOM tree to the root of the document. This means that the innermost element's event handler is executed first, followed by its parent's event handler, and so on up to the document's root.
Event Capturing: 
Event capturing is the reverse of bubbling. In this phase, the event starts from the root element and travels down the DOM tree to the target element. The event handlers on the root are executed first, followed by the handlers on their child elements, until it reaches the target element.
Here's a working example that demonstrates event bubbling and capturing:
Event Bubbling:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Event Bubbling and Capturing Example</title>
    <style>
                body {
                        padding: 50px;
                        background-color: cornsilk;
                }

                .outer {
                        width: 200px;
                        height: 200px;
                        background-color: lightblue;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                }
    </style>
</head>

<body>
        <div class="outer" id="outer">
                <button class="inner" id="inner">Click Me!</button>
        </div>

        <script>
                const outer = document.getElementById('outer');
                const inner = document.getElementById('inner');

                inner.addEventListener('click', function (e) {
                        console.log("inner clicked...");
                });
                outer.addEventListener('click', function (e) {
                        console.log("outer clicked...");
                });
                document.body.addEventListener('click', function (e) {
                        console.log("body clicked...");
                });
                // Output: inner clicked...
                //         outer clicked...
                //         body clicked...
        </script>
</body>
</html>
In the above example:
1. We have an HTML document with a div and button elements, div with the class outer and button with the class inner.
2. We attach event handlers to both the outer and inner elements and body for event bubbling.
3. When you click the inner button element, you will observe that event bubbling occurs by showing output in the console as inner clicked..., outer clicked... and body clicked....
We will show the event capturing in the next example.
Event Capturing:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Event Bubbling and Capturing Example</title>
    <style>
                body {
                        padding: 50px;
                        background-color: cornsilk;
                }

                .outer {
                        width: 200px;
                        height: 200px;
                        background-color: lightblue;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                }
    </style>
</head>

<body>
        <div class="outer" id="outer">
                <button class="inner" id="inner">Click Me!</button>
        </div>

        <script>
                const outer = document.getElementById('outer');
                const inner = document.getElementById('inner');

                inner.addEventListener('click', function (e) {
                        console.log("inner clicked...");
                }, true);
                outer.addEventListener('click', function (e) {
                        console.log("outer clicked...");
                }, true);
                document.body.addEventListener('click', function (e) {
                        console.log("body clicked...");
                }, true);
                // Output: body clicked...
                //         outer clicked...
                //         inner clicked...
        </script>
</body>
In the above example the capturing phase is enabled by passing true as the third argument to addEventListener. Now when you click the inner button element, it will trigger the caputring event as you can see in the output as body clicked..., outer clicked... and inner clicked....

What is Fetching Data and AJAX?

Fetching data and AJAX (Asynchronous JavaScript and XML) are techniques used in web development to retrieve data from a server and update a web page without requiring a full page reload. AJAX enables dynamic and responsive web applications by allowing data to be fetched and displayed in the background, without disrupting the user's experience. Instead of XML, modern applications typically use JSON for data exchange.
Here's a working example that demonstrates data fetching using AJAX in JavaScript:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Data Fetching with AJAX Example</title>
    <style>
                /* Style the container */
                .container {
                        text-align: center;
                        margin: 50px auto;
                        padding: 20px;
                        border: 2px solid lightgray;
                        width: 300px;
                }
    </style>
</head>

<body>
   <div class="container" id="content">
        <p>Data Will Be Loaded Here</p>
   </div>

   <script>
        // Function to handle data fetching and display
        function fetchDataAndDisplay() {
                const content = document.getElementById('content');

                // Create a new XMLHttpRequest (AJAX request)
                const xhr = new XMLHttpRequest();

                // Define the request method and URL
                xhr.open('GET',
                'https://jsonplaceholder.typicode.com/users/1', true);

                // Set up a callback for when the request is complete
                xhr.onload = function () {
                    if (xhr.status === 200) {
                         // Parse the JSON response
                         const data = JSON.parse(xhr.responseText);

                         // Display user data
                         content.innerHTML =
                            `Name: ${data.name}<br>Email: ${data.email}`;
                    } else {
                         content.innerHTML = 'Failed to fetch data.';
                    }
                };

                // Send the request
                xhr.send();
        }

        // Fetch user data and display it
        fetchDataAndDisplay();
   </script>
</body>
</html>
In the above example:
1. We have an HTML document with a <div> element with the class "container" and the ID "content." Initially, it contains a message indicating where the data will be displayed.
2. In the JavaScript section, we define a function fetchDataAndDisplay() that handles data fetching and display.
3. Inside the function, we create a new XMLHttpRequest object (xhr) to make an AJAX request.
4. We set up the request by specifying the request method (GET) and the URL to fetch data from (in this case, from a JSONPlaceholder endpoint).
5. We define a callback function (xhr.onload) to handle the response when the request is complete. If the request is successful (status code 200), we parse the JSON response and display it in the "content" element. Otherwise, we display an error message.
6. We send the AJAX request by calling xhr.send().
7. Finally, we call the fetchDataAndDisplay() function to initiate the data fetching and display process.
When you open this HTML page, it will fetch data from the specified URL (a JSONPlaceholder endpoint) and display the title and body of a post in the "content" element. This demonstrates how to use AJAX to fetch and display data without reloading the entire page.


What is BOM?

BOM, or Browser Object Model, is a set of JavaScript objects provided by web browsers to interact with the browser itself, its windows, and various browser features, excluding the web page's content (which is handled by the DOM, or Document Object Model). The BOM allows you to control the browser, access browser history, manipulate the window, and more.
Here's a simple working example that demonstrates the Browser Object Model:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Browser Object Model Example</title>
</head>

<body>
     <button onclick="openNewWindow()">Open New Window</button>
     <button onclick="closeWindow()">Close Window</button>
     <button onclick="navigateBack()">Go Back</button>

     <script>
        // Function to open a new browser window
        function openNewWindow() {
           // Open a new browser window
           const newWindow = window.open('https://www.example.com',
                                    '_blank', 'width=600, height=400');
        }

        // Function to close the current browser window
        function closeWindow() {
            window.close();
        }

        // Function to navigate back in the browser history
         function navigateBack() {
            history.back();
         }
     </script>
</body>

</html>
In the above example:
1. We have an HTML document with three buttons that trigger BOM-related actions: opening a new browser window, closing the current window, and navigating back in the browser's history.
2. In the JavaScript section, we define three functions:
openNewWindow(): This function opens a new browser window using window.open(). It loads the example.com website in a new browser window with specific dimensions.
closeWindow(): This function closes the current browser window using window.close(). Note that this may not work in all browsers, especially when the window was opened by JavaScript.
navigateBack(): This function navigates back in the browser's history using history.back(). It simulates clicking the browser's back button.
You can click the buttons to see the BOM in action. The "Open New Window" button opens a new browser window, the "Close Window" button tries to close the current window (behavior may vary depending on your browser's security settings), and the "Go Back" button navigates back in the browser's history.

Knowledge Check:

Here are 10 multiple-choice questions to test your knowledge about DOM manipulation in JavaScript:
Question 1: What does DOM stand for in JavaScript?
A) Document Object Model
B) Data Object Model
C) Document Order Model
D) Direct Object Manipulation
Show Answer

Answer 1: A) Document Object Model
Explanation: The DOM stands for Document Object Model, and it represents the structured content of an HTML document.


Question 2: Which JavaScript method allows you to find an HTML element with a specific ID?
A) getElementById()
B) getElementByTagName()
C) getElementByClassName()
D) selectElement()
Show Answer

Answer 2: A) getElementById()
Explanation: The getElementById() method allows you to find an HTML element by its unique ID.


Question 3: Which method is used to change the text content of an HTML element using JavaScript?
A) textContent
B) innerHTML
C) innerText
D) textContent.innerHTML
Show Answer

Answer 3: A) textContent
Explanation: You can change the text content of an HTML element using the textContent property.


Question 4: What is event delegation in DOM manipulation?
A) It involves delegating events to multiple elements.
B) It is a way to handle events on a parent element for its child elements.
C) It is a method to stop event propagation.
D) It refers to asynchronous event handling.
Show Answer

Answer 4: B) It is a way to handle events on a parent element for its child elements.
Explanation: Event delegation is a technique where you attach a single event handler to a common ancestor of multiple elements to manage events for those elements.


Question 5: How do you append a new element to the end of an existing HTML element using JavaScript?
A) appendChild()
B) addToEnd()
C) appendTo()
D) addEndElement()
Show Answer

Answer 5: A) appendChild()
Explanation: You can use the appendChild() method to add a new element to the end of an existing HTML element.


Question 6: Which method is used to remove an HTML element from the DOM using JavaScript?
A) remove()
B) deleteElement()
C) removeChild()
D) removeElement()
Show Answer

Answer 6: C) removeChild()
Explanation: The removeChild() method is used to remove an HTML element from the DOM.


Question 7: Which property allows you to get or set the value of an input element using JavaScript?
A) value
B) textContent
C) innerHTML
D) innerText
Show Answer

Answer 7: A) value
Explanation: The value property is used to get or set the value of an input element.


Question 8: What is the purpose of the querySelector() method in JavaScript?
A) To select the first element that matches a specified CSS selector
B) To select all elements in the DOM
C) To select elements by their IDs
D) To select elements by their class names
Show Answer

Answer 8: A) To select the first element that matches a specified CSS selector
Explanation: The querySelector() method allows you to select the first element that matches a specified CSS selector.


Question 9: Which method is used to add a CSS class to an HTML element using JavaScript?
A) addClass()
B) addClassName()
C) classList.add()
D) setClass()
Show Answer

Answer 9: C) classList.add()
Explanation: The classList.add() method is used to add a CSS class to an HTML element.


Question 10: What is the purpose of the innerText property in JavaScript?
A) It allows you to manipulate the inner HTML content of an element.
B) It retrieves or sets the text content of an element, including its descendants.
C) It is used to create new HTML elements.
D) It selects elements by their tag names.
Show Answer

Answer 10: B) It retrieves or sets the text content of an element, including its descendants.
Explanation: The innerText property allows you to retrieve or set the text content of an element, including the text content of its descendants within the element.

Comments

Popular posts from this blog

Part 9: Asynchronous Programming in JavaScript

Part 9: Asynchronous Programming in JavaScript Outline: 1. Introduction to Asynchronous Programming Definition of Asynchronous Programming Importance in Web Development Comparison with Synchronous Programming 2. Understanding JavaScript's Single-Threaded Model  Brief Explanation of JavaScript's Event Loop How Asynchronous Operations Fit into a Single Thread 3. Callbacks Explanation of Callback Functions Common Use Cases Callback Hell and Its Challenges 4. Promises Introduction to Promises as a Better Alternative to Callbacks Promise States: Pending, Fulfilled, Rejected Chaining Promises for Sequential Asynchronous Operations Error Handling with Promises 5. Async/Await Introduction to Async/Await as a Syntactic Sugar for Promises Writing Asynchronous Code in a Synchronous Style Error Handling with Async/Await 6. Event Listeners Asynchronous Nature of Event Listeners Handling User Interactions Asynchronously Examples of Asynchronous Event Handling 7. Timers and In

Learning JavaScript Step by Step - Part 7: Objects

Part 7: Objects in JavaScript What Are Objects? Objects in JavaScript are collections of key-value pairs. They're used to represent entities with properties and behaviors. Here's how you create an object: let person = {     name : " Alice " ,     age : 30 ,     isStudent : false }; 1. Curly braces {} define an object. 2. Each property is a key-value pair separated by a colon. Accessing Object Properties You can access object properties using dot notation or bracket notation: console . log (person . name) ; // Output: "Alice" console . log (person[ " age " ]) ; // Output: 30 Modifying Object Properties To change the value of an object property, simply assign a new value to it: person . age = 31 ; console . log (person . age) ; // Output: 31 Adding and Deleting Properties You can add new properties to an object or delete existing ones as needed: person . country = " USA " ; // Adding a new property delete person . isStudent ; /

Learning JavaScript Step by Step - Part 6: Arrays

Part 6: Arrays in JavaScript Welcome back to our JavaScript learning journey! In this part, we'll dive into one of the essential data structures: arrays. These are fundamental building blocks in JavaScript that enable you to work with collections of data and create more complex data structures. Creating Arrays An array is a collection of values, which can be of any data type, stored in a single variable. There are two methods of creating arrays in JavaScript: Method 1: Using Array Literals In this method, you directly list the elements you want to include within the array.This is the most common and convenient way to create an array. You define the array by enclosing a list of values inside square brackets []. Example: / Creating an array of numbers let numbers = [ 1 , 2 , 3 , 4 , 5 ] ; // Creating an array of strings let fruits = [ " apple " , " banana " , " cherry " ] ; // Creating an array of mixed data types let mixedArray = [ 1 , &quo

Learn JavaScript Step by Step Part 4 Control Flow

Part 4: Control Flow in JavaScript Welcome to the next part of our JavaScript journey! In this segment, we'll explore control flow in JavaScript. Control flow allows you to make decisions in your code and execute specific blocks of code based on conditions. It's a fundamental concept in programming. At the end of this blog you will get a quiz to test your understanding of this topic. Let's dive in! Conditional Statements: Making Decisions Conditional statements are used to make decisions in your code. They allow your program to take different actions depending on whether a certain condition is true or false. 1. If Statement:  The if statement is the most basic conditional statement. It executes a block of code if a specified condition evaluates to true. let age = 18 ; if (age >= 18 ) {     console . log ( " You are an adult. " ) ; } If you run the code in VS Code, the output will be: Output: You are an adult. 2. Else Statement:  You can use the else stateme

Learn JavaScript Step by Step Part 5 Functions

Part 5: Functions in JavaScript In this part, we'll dive into the exciting world of functions in JavaScript. Functions are like superpowers for your code. They allow you to encapsulate reusable pieces of logic, making your code more organized, efficient, and easier to maintain. We'll explore what functions are, how to declare them, and how to use them effectively. What Is a Function? Imagine a function as a mini-program within your program. It's a self-contained block of code that performs a specific task or calculation. Functions are designed to be reusable, so you can call them whenever you need that specific task done without writing the same code over and over. Declaring a Function: To declare a function, you use the function keyword followed by a name for your function. Here's a simple function that adds two numbers: function addNumbers ( a , b ) {     let result = a + b ;     return result ; } function: The keyword that tells JavaScript you're creating