1

I have a page that's contents are loaded from another html file using: var url = 'url.to.page'

fetch(url).catch(error => console.log('Authorization failed : ' + error.message));
$('body').load(url + ' #page-cover, .pre-load, header, .container');

Inside those elements are many other elements with ids and classes already assigned. They all show up when I inspect the page, but I can't select any of them without receiving 'null'. I've tried using:

document.getElementById("element");

$('[id^="element"]');

$('#element');

I have bound the function that calls this to wait until .load() sends a trigger that it has finished. Am I missing something, or is there a different way that dynamic elements need to be selected?

  • this question is incorrectly marked as a duplicate, user isn't asking how to bind to dynamic elements, they are asking why their selectors are returning null – RenaissanceProgrammer Dec 12 '18 at 18:14
  • @RenaissanceProgrammer because they don't exist at run time which is exactly what event delegation is used for. `load()` is an ajax method – charlietfl Dec 12 '18 at 18:15
  • works fine in the console on jquery.com, load in another jquery page into their homepage, jquery select an element from the loaded in page, works everytime, no event delegation needed to select an element – RenaissanceProgrammer Dec 12 '18 at 18:18
  • @charlietfl OP is trying to locate the dynamic elements, not bind events to them. eg maybe they want to `$("#element").hide()` ? – freedomn-m Dec 12 '18 at 18:18
  • Possibly related: https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – freedomn-m Dec 12 '18 at 18:18

1 Answers1

1

Both load() and fetch() are asynchronous

You can access newly loaded content in the load() success callback.

$('body').load(url + ' #page-cover, .pre-load, header, .container', function(){
  // new elements exist here

});
charlietfl
  • 164,229
  • 13
  • 110
  • 143