The issue arises when trying to apply Bootstrap CSS styles to dynamically created elements using JavaScript

I utilized JavaScript to create a Bootstrap Modal and followed the correct classes as outlined in the Bootstrap documentation, but unfortunately, the JavaScript-created elements are not being affected.

Even after adding the Bootstrap classes and attributes using the "classList.add()" and "setAttribute()" methods, the DOM elements remain unaffected.

The <!DOCTYPE html>, <html lang="en">, and other tags have been properly included as follows:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    
    <link rel="stylesheet" href="./index.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.3/css/bootstrap-grid.min.css" integrity="sha512-JQksK36WdRekVrvdxNyV3B0Q1huqbTkIQNbz1dlcFVgNynEMRl0F8OSqOGdVppLUDIvsOejhr/W5L3G/b3J+8w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.3/js/bootstrap.min.js" defer integrity="sha512-1/RvZTcCDEUjY/CypiMz+iqqtaoQfAITmNSJY17Myp4Ms5mdxPS5UV7iOfdZoxcGhzFbOm6sntTKJppjvuhg4g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="./index.js" defer type="module"></script>
</head>
<body>
    <div id="main">
        <div id="Open" class="block">
            <h2 class="block-heading">Open</h2>
        </div>

        <div id="In-Progress" class="block">
            <h2 class="block-heading">In Progress</h2>
        </div>

        <div id="In-Review" class="block">
            <h2 class="block-heading">In Review</h2>
        </div>

        <div id="Done" class="block">
            <h2 class="block-heading">Done</h2>
        </div>
    </div>

    <div type="button" id="addTask" data-bs-toggle="modal" data-bs-target="#exampleModal">
        <i class="fa-solid fa-circle-plus"></i>
    </div>

</body>
</html>

This is the JavaScript Code snippet-


export default function example() {
    console.log("Working");  // To verify if the function is working correctly.

    // Create the modal element
    const modal = document.createElement("div");
    modal.classList.add("modal");
    modal.setAttribute("tabindex", "-1");

    // Create the modal dialog element
    const modalDialog = document.createElement("div");
    modalDialog.classList.add("modal-dialog");
    modal.appendChild(modalDialog);

    // Create the modal content element
    const modalContent = document.createElement("div");
    modalContent.classList.add("modal-content");
    modalDialog.appendChild(modalContent);

    // Create the modal header element
    const modalHeader = document.createElement("div");
    modalHeader.classList.add("modal-header");
    modalContent.appendChild(modalHeader);

    // Create the close button and add it to the header
    const closeButton = document.createElement("button");
    closeButton.classList.add("btn-close");
    closeButton.setAttribute("type", "button");
    closeButton.setAttribute("data-bs-dismiss", "modal");
    closeButton.setAttribute("aria-label", "close");
    modalHeader.appendChild(closeButton);

    // Create the modal title and add it to the header
    const modalTitle = document.createElement("h4");
    modalTitle.classList.add("modal-title");
    modalTitle.innerHTML = "Modal Header";
    modalHeader.appendChild(modalTitle);

    // Create the modal body element
    const modalBody = document.createElement("div");
    modalBody.classList.add("modal-body");
    modalContent.appendChild(modalBody);

    // Add content to the modal body
    const modalBodyContent = document.createElement("p");
    modalBodyContent.innerHTML = "This is a small modal.";
    modalBody.appendChild(modalBodyContent);

    // Create the modal footer element
    const modalFooter = document.createElement("div");
    modalFooter.classList.add("modal-footer");
    modalContent.appendChild(modalFooter);

    // Create the close button and add it to the footer
    const closeButton2 = document.createElement("button");
    closeButton2.classList.add("btn");
    closeButton2.classList.add("btn-secondary");
    closeButton2.setAttribute("type", "button");
    closeButton2.setAttribute("data-bs-dismiss", "modal");
    closeButton2.innerHTML = "Close";

    const saveButton = document.createElement("button");
    saveButton.classList.add("btn-primary");
    saveButton.setAttribute("type", "button");
    saveButton.setAttribute("data-bs-dismiss", "modal");
    saveButton.classList.add("btn");
    saveButton.innerHTML = "Save";
    
    modalFooter.appendChild(closeButton2);
    modalFooter.appendChild(saveButton);

    // Append the modal to the body of the page
    document.body.appendChild(modal);
}

Answer №1

Consider updating the css link tag from bootstrap-grid to bootstrap so you can easily access the desired class.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Halt the script if the file has not been successfully loaded

Looking for a way to halt the script until $.get() has completed executing in this code snippet. $.get("assets/data/html/navigation.html", function(response) { $('body').append(response); }); $('body').append('<div class="m ...

What are the effects of calling callback(false) and callback(true)?

I'm currently diving into a nodejs chat project, and I’m a bit confused about the outcome when callback(false) and callback(true) are triggered in this context... io.sockets.on('connection', function(socket){ socket.on('new user& ...

Change the color of the menu icon based on the specified HTML class or attribute

I'm trying to create a fixed menu that changes color depending on the background of different sections. Currently, I am using a data-color attribute but I am struggling with removing and adding the class to #open-button. Adding the class works fine, ...

Cipher/decipher URL Redirect Parameter

While sending the return URL as a query string parameter, it looks like this: http://localhost:50316/TripNestFinal/Login.aspx?ReturnUrl=~/Account/AccountSettings.aspx However, I am seeking a way to encode ~/Account/AccountSettings.aspx in a manner that wi ...

What could be the reason for the next.js Script tag not loading the third-party script when using the beforeInteractive strategy?

I have been trying to understand how the next.js Script tag with the beforeInteractive strategy works. I am currently testing it with lodash, but I keep encountering a ReferenceError: _ is not defined. I was under the impression that when a script is loade ...

Issue encountered while attempting to adjust a date (the modification was incorrect)

I am currently working on developing a calendar feature using Angular. Part of this project involves implementing drag and drop functionality to allow users to move appointments from one day to another. However, I have encountered a strange issue. When at ...

Why won't hover over function properly in separate divs for two items?

My goal is to show text when hovering over a logo, but the text and logo are in different divs. Despite trying various solutions like using display: none and display: block, I still can't get it to work. import styles from '../styles/Float.module ...

delay of Paypal API disbursement for transactions with a range of money values

After browsing through various resources such as this link, that link, and another one on the PayPal developer website, I attempted to implement a payment processing system that allows users to approve a preset amount of money. Similar to services like Ube ...

Create a new instance of the TypeScript singleton for each unit test

I have a TypeScript singleton class structured like this: export default class MySingleton { private constructor({ prop1, prop2, ... }: MySingletonConfig) { this.prop1 = prop1 ?? 'defaultProp1'; this.prop2 = prop2; ...

Error message: Please provide an expression with const in React JS component

Can you assist me with this issue? I am trying to determine if the user is registered. If they are registered, I want to display the home URL, and if they are not registered, I want to display the registration URL. To do this, I am checking the saved dat ...

Display results in a Web application using Google Apps Script

function doGet() { return HtmlService.createHtmlOutputFromFile("vi"); // var output = HtmlService.createHtmlOutput('<b>Hello, world!</b>'); } function doPost() { return HtmlService.createHtmlOutputFromFile("vi"); // var out ...

Node JS does not receive a response from JQuery Ajax

I have developed a form on the client side which includes: <html> <body> <script> $(document).ready(function() { $.ajax({ url: "Search.html", type: "POST", dataType : "json", s ...

Show a string on different lines

I'm looking to format my string so that it displays on multiple lines. I attempted to use replaceAll(",", "\n"), but it didn't work as expected. Here's the code snippet: <template> <v-form> <v-container> ...

extracting values from deeply nested JSON array in JavaScript

Is there a way to extract values from a deeply nested JSON array? I'm looking to retrieve all pairs of (nameValue and value) from the JSON provided below var json = [{ name: 'Firstgroup', elements: [{ ...

What is the best way to calculate the duration of a .wav file stored locally using JavaScript?

Can you help me figure out how to determine the duration (in milliseconds) of a .wav file using JavaScript for a GreaseMonkey Script? The main challenges I'm encountering are: 1) Accessing local files 2) Retrieving the length of the wav file ...

What is the best way to emphasize the current page within my Bootstrap <nav> menu?

Below is the Bootstrap code that defines our main menu navigation: <div class="col-xl-9 col-lg-9"> <div class="main-menu d-none d-lg-block"> <nav> ...

Modify the parent scope variable within an Angular directive that contains an isolated scope

Here is a directive implementation: <some-directive key="123"></some-directive> This directive code looks like this: angular.module('app').directive('someDirective', ['someFactory', '$compile', '$ ...

Tallying responses of "Yes" and "No" in a React form and storing them

I'm currently working on a React form using Material UI components. To keep track of the responses, I have an empty array called questionAns. My goal is to append an element like yes to the array when the Yes radio button is selected in the form. Belo ...

Should I include JSX or JS when exporting ReactJS components as node modules to npm?

I've been busy developing React.js components and sharing them as modules on npm. My approach involves utilizing a gulp task to convert all jsx components into js, leveraging gulp-react: var react = require('gulp-react'); gulp.task(' ...

The Bootstrap Modal will still appear even in the presence of a validation error

Recently, I created a sign-up page using HTML and Bootstrap 5. To ensure data validation on the form, I integrated Bootstrap's validation feature. However, after completing the registration process, a modal pops up as intended. The only issue is that ...