Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
166
rated 0 times [  170] [ 4]  / answers: 1 / hits: 29289  / 11 Years ago, tue, september 24, 2013, 12:00:00

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!


More From » jquery

 Answers
16

For the sake of thoroughness and bringing a clear solution to my question to light, herewith my conclusion. Thank you all for your thoughts and suggestions, I've learnt a lot and clearly got people thinking!



Initially I was hoping for a magical jQuery function that I'd perhaps overlooked, something along the lines of:



$(#parent-element).monitorDom(function(added_element){ ... });


...but there just isn't anything, which is probably a good thing because I suspect I've stumbled onto poor code design, and allowing for hooks and callbacks is a better way to go. I.e.: use the smaller, established and tested building blocks instead of trying to over-engineer something.



If you don't care about supporting Internet Explorer and it's quirks, you may definitely look at the deprecated mutation events, or their replacement the MutationObserver. Here is also a decently answered SO question with the use of mutators: Is there a JavaScript/jQuery DOM change listener?



In a nutshell, as of this post, there is no built-in jQuery function to monitor DOM changes, and in my case my problem can be resolved with better code design. Thank you all for all the answers, and let's keep pushing the limits!


[#75470] Monday, September 23, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaylynbrynnk

Total Points: 706
Total Questions: 98
Total Answers: 91

Location: Israel
Member since Thu, Jan 7, 2021
3 Years ago
;