Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding custom CSS classes to dynamically-created elements with jQuery

Let me illustrate my question: I have an external JavaScript library that creates certain HTML elements for me dynamically based on user input and interaction, and I'm looking to write a script that would automatically add a certain class to these dynamically created elements. Assume that I also am unable to edit the external JavaScript library I'm using.

Is this elegantly possible? If so, how? If not, could this be a side-effect of poor implementation design?

I've thought about somehow monitoring the DOM to see when it was updated, and adding the classes to these new elements then, but this seems cumbersome and possibly unnecessary.

Thanks in advance for any thoughts / solutions!

Edit:

As requested, here's a simplified example of what I'm trying to accomplish with a code sample:

// function in external library, assume it cannot be edited!
function addElement() {
    $('body').append($('<div class="newly_created_element"></div>'));
}

// my code, looking to add the class name to the newly-created elements
// from the external function above...
// pseudo-coded as I have no idea how to do this!
$(function(){
    when (new element added) {
        add class "my_own_class";
    }
});

I hope this makes sense!

like image 999
Chris Kempen Avatar asked Sep 24 '13 11:09

Chris Kempen


2 Answers

You can do something like:

$("body").bind("DOMNodeInserted", function() {
   $(this).find('.newly_created_element').addClass('my_own_class');
});

See more on DOMNodeInserted here

like image 82
MaVRoSCy Avatar answered Oct 12 '22 23:10

MaVRoSCy


Hi I made a jsfiddle dealing with your issue. The click on the button simulates your external libary adding a element. Unrelated to the button click I'm listening on DOMNodeInserted. If there is something inserted in the dom a class is added. You could easily modify the script to only add a class to certain elements.

http://jsfiddle.net/kasperfish/AAd8f/

$(function() {
    $('#btn').click(function(){
        $('body').append('<div style="width:30px;height:30px;border:1px solid black"></div>');
    });


    $(document).on('DOMNodeInserted', function(e) {

        $(e.target).addClass('blue');
    });


});
like image 44
kasper Taeymans Avatar answered Oct 13 '22 00:10

kasper Taeymans