Home > Back-end >  Javascript is not working properly inside djagno project
Javascript is not working properly inside djagno project

Time:07-06

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

<!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>

CodePudding user response:

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.

  • Related