NarulaKeshav NarulaKeshav - 20 days ago 6
CSS Question

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
?

Answer

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>