Via a click event, I injected an element with a custom attribute
<div class="added" myValue="hello"></div> to the DOM.
I wrote a generic function:
$('.added').each(function(){
console.log( $(this).attr('myValue') );
});
Doesn’t work. I thought $.each() can handle dynamic elements?
UPDATE to the question:
I realize using .each() is the wrong approach. But what to do if I don’t want to attach an event handler to the element. I just want to automatically do stuff to any elements of a certain class name, regardless of when they’ve been added to the DOM. Seems like a common use case.
When your click event happens, do your “something” there.
ID’s must be unique, so i changed added to a class.
If you want to separate the two, have your click event trigger an event, then use event delegation to listen for it.
$.eachdoes not work with future elements, only the elements that exist when the code is executed.Update for question Update
That simply isn’t possible without writing inefficient code. It would require either using DOMMutationEvents which can be inefficient, are depreciated, and are not supported in all browsers, or you can use a setInterval which is also inefficient because it would be constantly running searching the dom for new elements.