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!
You can do something like:
$("body").bind("DOMNodeInserted", function() {
$(this).find('.newly_created_element').addClass('my_own_class');
});
See more on DOMNodeInserted here
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');
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With