Reputation: 59
I'm trying to target multiple items on a page that are loaded dynamically via javascript. The code I'm using is below and it works fine if the items are present in the DOM on load.
$(".target-item").each(function(i, element) {
var innerURL = $(this).html()
$(element).html("<img src='"+ innerURL + "'>");
});
Is this possible to do?
Upvotes: 1
Views: 1011
Reputation: 2652
The code you posted will only ever work on the DOM elements currently on the page. That's the nature of scripting, it runs once and then it's over -- so anything you add later to the page will be unaffected.
You mentioned that something in your WordPress theme/plugin is responsible for adding those items to the DOM. The easiest way would be to look into that js and see if there's a way to integrate with it. Does it trigger an event after it does this (you could listen for the event and then do your thing)? Does it let you specify a callback function to be run after it does this (you could give it your img src logic as a function)? If there's no way to integrate with it ... well, that's the downside of using third-party code.
However, I think you should be able to call this logic when the elements have been added to the page, regardless of how it happens. Every DOM element triggers a 'load' event when it's loaded into the page, so you can listen for that. The elements don't exist yet, though, so you can't bind an event listener to them -- you have to use event delegation, and bind an event to the target element's parent. Here's how it might look:
var targetParent = jQuery('.some-div-that-contains-dynamic-elements');
targetParent.on('load', '.target-item', function() {
var $this = jQuery(this);
var innerURL = $this.html();
$this.html("<img src='"+ innerURL + "'>");
});
Here you're binding an event listener on the element that contains your target-items. When a new target-item is added to the DOM, it's load
event fires, bubbles up to the parent, and triggers the event handler.
Upvotes: 1
Reputation: 444
So you have a div or something and inside is your url that you replace with an img element right? And the Problem is that you don't know wich one is already replaced?
If I'm right than you can use ".target-item :not(:has(img))". With that selector you will get all elements that has the class .target-item but no img element as child.
Upvotes: 0