Issues with Javascript queryselectors not recognizing classes and IDs within Django projects

While I'm working outside of a Django file, everything runs smoothly with JavaScript reading classes and IDs like:

document.querySelector('.class_name').addEventListener

However, when loaded within Django projects, an error occurs stating that the event listener cannot read NULL.

{% comment %} CSS file for contacts.html {% endcomment %}
<script type="text/javascript" src="{% static 'info/js/for_recrs.js' %}"></script>
<link href="{% static 'info/css/for_recrs.css' %}" rel="stylesheet" type="text/css" />
{% endblock %}

Answer №1

When you declare a JS file in the head section, it reads it immediately without referencing the HTML file first. This can result in reading null values for classes and IDs. To prevent this issue, you can declare the script file just before the end of the body tag. OR You can use

window.onload = function() {
// write your code here.
}

This solution worked for me.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determine the minimum height for rows without compromising the automatic height feature in Ag-grid

My goal is to set a minimum height of 40px for each ag-grid row while allowing dynamic height for rows exceeding this minimum. this.gridOptions = { /* rowHeight : 40, */ headerHeight: 100, pagination: true, enableSort ...

Transitioning from one CSS id to another during page loading

Wondering how to fade in one CSS id on page load and then smoothly transition to another after a few seconds? Here are the ids: #background { background: url("images/am_photography_bg.jpg") no-repeat center -25px fixed; background-size: 100%; ...

What is the process for creating a fresh database with the MongoDB Node.JS driver?

Is there a way to create a new database programmatically using the MongoDB Node.JS driver? I came across some code that seems to be promising, but I'm uncertain about how to connect with admin credentials and actually create a new database. var db = ...

Generate an array by collecting all the DIV elements, then proceed to compare for any

I need to create a form that checks if the user has entered a specific word in a textarea. These words are stored in arrays generated from divs. I am having trouble with the verification part, and I believe my arrays may not be created correctly. Take a l ...

Unintended repetition with fetch() for loading a texture

I've been experimenting with using the fetch statement to fetch a local image and incorporate it into my (three.js) project. However, I seem to have created an infinite loop and I can't figure out why. Since the project is quite large, I've ...

What is the best way to ensure consistent code placement at the bottom of my Django Template using inheritance?

Lately, I've been working on incorporating a footer into my layout.html file that is inherited by all other pages within my Django project. I am aiming to create a footer that remains fixed at the bottom of every webpage just like how Stack Overflow ...

Responsive Menu is not compatible with the Carousel Image Slider

Hey there, Developer Community! I recently delved into programming a few days back and decided to create a homepage for an artist. The page features a responsive menu that switches to a dropdown menu with a button when the screen size shrinks. It also inc ...

Different types of forms displayed together with a sole submission button in a separate section

https://i.sstatic.net/aAbD9.jpg My webpage consists of two main sections: the red section which is a partial view containing actions for forms, and the blue section which contains tabbed forms. Each tab in the blue section is also a view, called using the ...

Is it possible to send properties to a React Component using a regular function?

import C from './C.js'; const Solution = () => { async function fetchData() { await axios .get(`http://localhost:2000/?url=${link}`) .then((response) => { <C data={response.data} / ...

Prevent the date in Django from being changed

Currently in the process of creating a blog using django. I have set up an Entry class which includes fields for title, content, publish date, and more. The issue I am facing is with the date field - it saves the date when the entry is created, but update ...

During POST requests, validated data undergoes validation in the .create() method of a nested serializer, resulting in the

: bought_items = validated_data.pop("items") KeyError: 'items' I established a Many-to-Many relationship between Items and Purchase. My goal is to automatically populate the BoughtItems (the through model) whenever a purchase is made. ...

Navigating JWT Authentication and Managing Deactivated Users in Django Rest Framework

My goal is to free up a username for reuse once a user deletes their account. Currently, the username remains unique even after an account is soft deleted, as per the default setup in Django. To achieve this, I need to modify the uniqueness of the usernam ...

Why does jQuery val() function fail to clear readonly input date in Firefox but succeed in Chrome?

When using JQuery.val(''), I noticed a difference in behavior between Firefox and Chrome. You can see the issue demonstrated in this jsfiddle: https://jsfiddle.net/mdqfbj/d4eovkg8/3/ A JS function triggered by a radio button is supposed to clea ...

The script fails to load when utilizing jquery/ajax

After the page loads, I am attempting to dynamically add a script into a div using ajax/jquery. This particular script is sourced from a CPM network and is responsible for loading a banner. However, when I try to load this script through ajax post-page lo ...

What is the best way to test the PasswordChangeView in Django?

I have been working on creating a test for the get_success_url method in PasswordChangeView to ensure that the redirect functionality is working correctly. My desired outcome, when using valid form data, is to successfully change the password and receive ...

Having trouble with my Bootstrap 4 navbar button - what am I doing wrong?

After conducting research online, I found myself unable to resolve my issue due to my lack of proficiency in English. I apologize for any confusion caused and would like to revisit the topic. The problem lies with my navbar toggle that is not functioning ...

Leverage the power of index to slice through an array in Apps Script

Having recently transitioned from Matlab to apps script, I am facing a challenge with subsetting arrays. Specifically, I need to filter the array "names" based on the values in another array called "index", which are of equal length: names = [["name1"], [ ...

Press the "Reveal More" button to expand the content to its full size

I am currently working on coding a "read more" section using a button. I have looked at some existing solutions, but none of them are to my liking. My plan is to create a div that includes all the relevant content. My goal is to have a div at the bottom w ...

Angular Checkbox Plugin

I'm currently working with Angular and I seem to be facing an issue that may be related to it. I have a checkbox that functions properly when clicked, but the problem arises when I select another item. It seems like the checkbox retains its previous ...

Passing query string parameters to a state's templateUrl in AngularJS using ui-router

Is it possible to pass the query string to templateUrl when the html is generated by a Django view in this scenario? I am attempting to pass parameters (itemId) to the templateUrl in angularjs ui-router as shown below: .state('MyApp.itemEdit&ap ...