简体   繁体   中英

How to render html from a external js file

This might be a dumb question but I have actually never done this and what I am trying is not working.

I have 2 files

test.html
test.js

I am linking the js as an external in test.html

<!doctype html>
<html>
<head>
<script type="text/javascript" src="test.js"></script>

<meta charset="utf-8">
<title>Untitled Document</title>
</head>

<body>
</body>
</html>

In my js file I have something like this

document.appendChild('<div>testing</div>')

I also tried

document.getElementsByTagName('body').appendChild('<div>testing</div>')

What I am doing wrong? I just want to learn how to generate html from an external js file for a future project I am working on.

You should generally try to run scripts that depend on the page after the document has been parsed, not before - if you put the script in <head> and run it immediately, the <body> has not been created yet. Give your script tag the defer attribute so that it only runs after the document is fully parsed:

<script defer type="text/javascript" src="test.js"></script>
  • appendChild accepts an element as a parameter, not a string

  • You need to append to the body , not the document itself ( Only one element on document allowed. )

  • If you want to append an HTML string, assign/concatenate to the .innerHTML property

  • Assigning to .innerHTML will corrupt existing references to elements inside, including listeners. In order to keep listeners active, use insertAdjacentHTML instead:

 document.body.appendChild(document.createElement('div')) .textContent = 'testing1'; // Another method: document.body.innerHTML += '<div>testing2</div>'; // Another method: document.body.insertAdjacentHTML('beforeend', '<div>testing3</div>'); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM