0

When i click a button on index.html to load test.html dynamically, the javascript which is written in test.html does not work.

test.html below.

<p>Test for dinamic loaded javascript</p>
<button id="testButton"></button>

<script>
    const testElem = document.querySelector('#testButton');
    testElem.addEventListener('click', testFunction);

    function testFunction() {
        alert('Hello World');
    }
</script>

the script below loads test.html dynamically.

fetch('/test.html').then(function(response) {
  return response.text();
}).then(function(string) {
  const laden = document.querySelector("#demo");
  laden.innerHTML = string;
  console.log(string);
}).catch(function(err) {  
  console.log('Fetch Error', err);  
});
Mugé
  • 452
  • 3
  • 15
Jan
  • 1
  • 1
  • What do you get if you try to console.log `testElem`? Is your html rendering? Is the JS running at all? – jmargolisvt Jan 12 '20 at 17:36
  • Hi Jan, welcome to stackoverflow. I have done a minor typo correction. I also added the Tag 'html' to your search. If you do not agree with the change, just reverse the corrections. – Mugé Jan 12 '20 at 17:39
  • This is intended behaviour. There are ways to make it work. See duplicate references. – trincot Jan 12 '20 at 17:40
  • @Mugé Thanks. My english language is not too good. – Jan Jan 12 '20 at 20:04
  • @Jan It is not to criticize your post. Stackoverflow gives us points when we edit a text or add a Tag to your post. The tag helps in indexing and also to quickly see if we can help you with your question, and more. Your English is just fine. It was a very little correction. – Mugé Jan 12 '20 at 20:10
  • @jmargolisvt In the console nothing happens. The html is rendering. The javascript is displayed in the demo div between the script tags. But does nothing at all. – Jan Jan 12 '20 at 20:10

0 Answers0