Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript is not working properly inside djagno project

While my code is working when used outside of a Django project, when I place it inside one it’s acting strange.
More specifically, the document object does not have a body, but only the head of my html. Thus I am not able to access its classes. My guess is that something’s wrong in the linking between the html and js files.

settings.py

STATIC_URL = 'static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]

index.html

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>index.html</title>
    {% load static %} 
    <link rel="stylesheet" href="{% static 'style.css' %}"/>
    <script src="{% static 'script.js' %}"></script> 
</head>
<body>
    HelloWorld!
</body>
</html>

script.js

console.log(document.getElementsByTagName('html')[0].innerHTML)

The return of script.js:

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>index.html</title>
     
    <link rel="stylesheet" href="/static/style.css">
    <script src="/static/script.js"></script></head>

>Solution :

You should wait until your HTML completely loaded and parsed before accessing it.

Just wrap your script by

window.addEventListener('DOMContentLoaded', (event) => {
    console.log(document.getElementsByTagName('html')[0].innerHTML)
});

or place your script right before the closing </body> tag.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading