简体   繁体   中英

Change CSS of dynamically created elements via jQuery

I'm trying to change the color of the h3 within my div .card that was dynamically created, however, when I reload the page, it sets its values to default.

This is how I'm trying to change the color where color in parameter is the desired color to apply to the h3 .

On button click, I'm creating the card:

function createCard(id, title, ...) {
    // Creates a main card div
    var $cardDiv = $('<div>', {
        class: 'col-md-12 card',
        "card-id": id
    });

    // h3 tag with title of note
    var $title = $('<h3>', {
        "data-toggle": 'modal',
        "data-target": '#update',
        click: function() {
            updateModal(id, title, note);
        }
    }).text(title);

    // Append to card
    $cardDiv.append($title);
}

After this, I'm calling the cardScheme method:

cardScheme('#29ABDA');

function cardScheme(color) {
    $('.card h3').css('color', color);
}

I realized that JavaScript/jQuery are unable to find the .card class since those cards were created dynamically.

var cards = document.getElementsByClassName('card');
for (var i in cards) {
    console.log('cards', cards[i]);
}
// returned {cards, 0}

How can I change the color of the h3 ?

You can call the cardScheme('#29ABDA'); inside the createCard method as below.

Note : I can't see where you are appending the dynamic div $cardDiv to the document, I mean to another existing div or body .

Working snippet :

 function cardScheme(color) { $('.card h3').css('color', color); } function createCard(id, title, note) { // Creates a main card div var $cardDiv = $('<div>', { class: 'col-md-12 card', "card-id": id }); // h3 tag with title of note var $title = $('<h3>', { "data-toggle": 'modal', "data-target": '#update', click: function() { updateModal(id, title, note); } }).text(title); // Append to card $cardDiv.append($title); $('#container').append($cardDiv); cardScheme('#29ABDA'); } setTimeout(function(){ createCard('test', 'testTitle', 'test note'); }, 2000); // after 2 seconds 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="container"></div> 

You should add your JS code once the DOM is being loaded and ready to use. Like this -

$(document).ready(function(){
    $('.card h3').css('color', color);
});
function createCard(id, title, ...) {
      ...
     // append this below the initial code you've
    //.ready make sures that function within is executed only when the specified HTML element is created in DOM
    $($title).ready(function(){
         //Then call your function
        cardScheme('#29ABDA');
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM