-1

I have the following jQuery code:

$('.class-name').each(function() {
    $(this).parent().prepend(this);
});

So it targets .class-name and works fine on page load.

I want it to also target any elements that is added dynamically (after page load) with class .class-name.

How can I do this?

Henrik Petterson
  • 6,862
  • 20
  • 71
  • 155
  • Put that code in a function, then call it again after you add the new dynamic content - or better yet, include the prepended data in what you actually add to the DOM in the first place – Rory McCrossan Feb 22 '17 at 14:14
  • 1
    @RoryMcCrossan The dynamically added elements are added by a third-party function and happens quite randomly. – Henrik Petterson Feb 22 '17 at 14:15
  • That is information that's vital to your situation which should really be in the question. Does the third party function expose any events when content is added? If so you should call `prepend()` within that event. If not, look in to using MutationObservers, although note that they are not fully supported in all browsers. – Rory McCrossan Feb 22 '17 at 14:15
  • @NenadVracar there's no click event handler in the OPs code. – Rory McCrossan Feb 22 '17 at 14:17
  • @RoryMcCrossan Any way I can find out if the third-party function is exposing any events without looking into the (very messy) code? – Henrik Petterson Feb 22 '17 at 14:20
  • I'd hope they have some documentation online somewhere you can refer to – Rory McCrossan Feb 22 '17 at 14:21
  • @RoryMcCrossan Is there no way to track/listen into the events and find it out that way? – Henrik Petterson Feb 22 '17 at 14:26

1 Answers1

0

Use on handler to dynamically target newly added elements on the page.

$('document').on('event', '.class-name' function() {
    $(this).parent().prepend(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Rikin
  • 5,351
  • 2
  • 15
  • 22