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

3
  • Maybe I'm not understanding what you mean, but can't you just do: $('#content').html("20"); Commented Aug 11, 2021 at 18:21
  • within inc.html you can but not within index.html Commented Aug 11, 2021 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. Commented Aug 11, 2021 at 18:43

1 Answer 1

1

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

$('#targetDiv').load( 'includes/inc1.html', function(){
    $('#content').html("20");
});
Sign up to request clarification or add additional context in comments.

5 Comments

Nice! Worked a treat. Thanks for taking the time to help out!
Quick follow up. I have decided to use the code at stackoverflow.com/questions/68762878/… 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 jsfiddle.net/Twisty/hpd415fj/46 so It executes against the the loaded file inc_1.html. Thanks
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.
ok thanks Phaelax z. Trying to figure it out here: stackoverflow.com/questions/68772110/… . Fingers crossed
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(){...});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.