0

If I have a template index.html and use jquery.load to include a file with html e.g $('#targetDiv').load( 'includes/inc1.html' ); into it. How do I target the content in inc1.html with both javascript and jQuery from within index.html

let's say inc1.html contains <div id="content">10</div> and I want to change the value from 10 to 20 using document.getElementById("content").innerHTML = "20"; within the script tags in index.html? Thanks

  • Maybe I'm not understanding what you mean, but can't you just do: $('#content').html("20"); – Phaelax z Aug 11 '21 at 18:21
  • within inc.html you can but not within index.html –  Aug 11 '21 at 18:24
  • I haven't used load() before but from what I read it's asynchronous, so the dom objects might not exist yet in index.html when trying to get the element. Use the load's callback function which is called when the task is actually complete and change the element from there and see if that works for you. – Phaelax z Aug 11 '21 at 18:43

1 Answers1

1

What I suggested in the comments about setting a callback function.

$('#targetDiv').load( 'includes/inc1.html', function(){
    $('#content').html("20");
});
Phaelax z
  • 1,814
  • 1
  • 7
  • 19
  • Nice! Worked a treat. Thanks for taking the time to help out! –  Aug 11 '21 at 19:10
  • Quick follow up. I have decided to use the code at https://stackoverflow.com/questions/68762878/loading-html-files-with-dropdowns-using-jquery/68762912#68762912 to load my HTML files. How would I amend this jQuery in the parent page so I could target the loaded HTML page inc_1.html with further jQuery code. I'd like to be able to run the jQuery at https://jsfiddle.net/Twisty/hpd415fj/46/ so It executes against the the loaded file inc_1.html. Thanks –  Aug 12 '21 at 20:23
  • Any jquery you want to use on the inc_1.html page has to be after the page is loaded into the DOM. You can put all your logic into another function then call it from the callback used in load(), same as how we set the inner html of the #content element. – Phaelax z Aug 13 '21 at 12:20
  • ok thanks Phaelax z. Trying to figure it out here: https://stackoverflow.com/questions/68772110/dom-issues-using-jquery-load-how-to-load-html-file-into-main-html-template?noredirect=1#comment121539642_68772110 . Fingers crossed –  Aug 13 '21 at 12:49
  • Adding something like `$('#content').html("20");` I can do but I've no idea how to add a large chunk of js in a function inside in ... `$('#targetDiv').load( 'includes/inc1.html', function(){...}); –  Aug 13 '21 at 13:40