Troubleshooting issues with applying a class on load using JavaScript

I am new to Javascript and I am trying to add a class to an element when the page loads. Specifically, I want to change the background color of the element as a test. However, I keep running into the error message "Uncaught TypeError: Cannot read property 'classList' of null."

I know that I must be missing something simple here. Any advice would be greatly appreciated.

Thank you in advance

window.onload = onPageLoad();

function onPageLoad() {
    document.querySelector('.home').classList.add = ('active');
}
.bg-yellow {
  background-color: yellow;
}

.active {
  background-color: green;
}

div {
  height: 400px;
  width: 400px;
}
<div class="bg-yellow"></div>

Answer №1

To start, it's important to remove the parentheses from window.onload = onPageLoad(); when assigning it, otherwise it will be invoked immediately.

Secondly, the correct syntax is .classList.add('active');, not .classList.add = ('active');.

Lastly, make sure you are using the class selector .bg-yellow for your element, not .home.

Check out the stack snippet below:

window.onload = onPageLoad;

function onPageLoad() {
    document.querySelector('.bg-yellow').classList.add('active');
}
.bg-yellow {
  background-color: yellow;
}

.active {
  background-color: green;
}

div {
  height: 400px;
  width: 400px;
}
<div class="bg-yellow"></div>

Answer №2

To correct the issue, remove the equals sign. From what I remember, .add() is a function that should be utilized. It might be worth looking for .bg-yellow instead of .home in the querySelector function based on your code examples. Alternatively, you could add 'home' to the classes of the .bg-yellow div like this:

<div class='bg-yellow home'><div>
.

The reason for the error message you are encountering is likely due to the fact that .home does not exist on your page as indicated by the sample provided. Therefore, when searching for that selector, .querySelector will return null (refer to the standard) and there will be no classList defined for null objects.

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

Passing a service into a directive results in an undefined value

Can someone help me understand why a service I am injecting into a directive is returning undefined in certain instances? If you would like to take a look at the code, here is a plunker link: https://plnkr.co/edit/H2x2z8ZW083NndFhiBvF?p=preview var app = ...

When using the android phonegap application, the screen interface may not render properly and display a patch on the keypad area when the keypad is

Whenever I tap on a textbox, the system keypad pops up. But after entering text, if I click on any link instead of pressing the Go button on the keypad, the keypad disappears but leaves behind a random area or displays the previous screen. When navigating ...

Building a Directory with Cordova Application

I am currently in the process of developing a Cordova App on my own and I'm facing an issue with creating a new folder to save images in the internal storage of the phone. Despite reading various online articles, I have not been successful in finding ...

Creating a popup window for multiple file uploads in ASP.NET using VB.NET

Hello, I am trying to create a popup window with multiple file upload options. When the 'UploadDocument' button is clicked, I want the popup window to appear. I have attempted to do this but it is not working as expected. Currently, the popup ap ...

React Routes displays single route at a time

Every time I attempt to link components with routes and input more than one route within <Routes>, React seems to disregard them and does not respond at all. I even tried using <StrictMode> to examine what is going on within the program. Here i ...

Looking to retrieve a JavaScript code block from an AJAX response using jQuery?

How can I extract a Javascript code block from an ajax response using jQuery, while disregarding other tags (in this case, the div tag) and prevent the execution or evaluation of the Javascript code? Example in get_js.html: <script> $(function ...

What is the best way to create a CSS flexbox row that does not span the full width of the screen?

Looking to display 4 images in a grid layout of 2 by 2, I'm trying to avoid having each image take up 50% of the screen for aesthetic reasons. Any suggestions on how to achieve this? I've attempted setting the flex-direction to column, but it re ...

Nextjs is having trouble loading the Infogram script

Struggling to insert an Infogram into my project by pasting the script but it's not working as expected. All other scripts in _app.js are functioning properly, however, this particular script isn't loading the graphic even though it appears when ...

Tips for accessing the firebase user's getIdToken method in Next.js after a page reload

Currently, I am developing a Next.js project and implementing user authentication using Firebase's signInWithPhoneNumber method for phone number verification. After successful verification, I receive a Firebase user with the getIdToken method to retri ...

Using jQuery to merge various .HTML elements and set their attributes

A series of values received through ajax are stored in this data variable, such as: $("#datset_egn").html(data['egn']); $("#datset_tabnomer").html(data['tab_nomer']); $("#datset_vhnomer").html(data['vh_nomer']); $("#datset_po ...

Guide to setting a default child route in react-router and updating the URL as needed

Currently, I am utilizing react-router v3 and have a segment of my routing code as follows: ... <Route path='dashboard' component={Dashboard}> <Route path='overview' component={Overview}/> <Route path='scan&apo ...

Button in Angular requiring double-click to trigger the click event

Currently, I am in the process of building an application using Angular. The module I am focusing on allows users to either join an existing room or create a new one. Here is the initial UI design of the room module: https://gyazo.com/81afe2b5f7119326d00b ...

Overlaying content: Innovative dropdown menu design

My goal is to create a dropdown box that overlays the content of a div when an icon within it is clicked. However, currently, the dropdown box is pushing down the content of the div instead of overlaying it. I have tried adjusting my CSS by setting some el ...

Are you looking to convert this JSON using underscore or any other JavaScript utility tool?

Looking at this JSON data: [{"target": "mydata.12.2", "datapoints": [[763.7, 1368821100], [762.1, 1368821160], [223.11, 1368821220], [886.54, 1368821280], [112.3, 1368821340]]}] I need to strip the first key and square brackets so it appears like this: ...

Having trouble storing radio buttons and checkboxes in MySQL database using AJAX

My app is facing an issue where radio buttons and checkboxes are not correctly entering information into the database. Currently, only text fields are successfully saving data, while checkboxes and radio buttons are only recording the value of the first ra ...

Does anyone have any firsthand experience with Internet Explorer performing poorly on a VPS?

Our team recently completed a portal project that is now live and operational. After thorough testing, everything seemed to be working perfectly until a customer used Internet Explorer with Citrix VPS, causing the page to take 12 seconds to fully load. Co ...

Generating dynamic div elements in a Laravel blade template using a foreach loop

After receiving an object from the controller to the blade using compact, I am utilizing it in my blade file to display the data. <div class="col-lg-4 col-md-4 col-xs-12 col-sm-6"> <!-- This must regenerate to print next 4 entries--> ...

The text rests on a slanted div with a captivating background image

How can I place text over a skewed div with a background image? Despite using the ::before pseudo element, the text is appearing behind the image. Here's an example of what I'm attempting to achieve: Html <div class="diag-right">Text Here ...

Issue with line wrapping due to padding-left in IE7

My <font> element is having line wrapping issues in IE7, where padding-left:30px; or margin-left:30px only affect the first line. Unfortunately, since it's a web-app, I can't replace the <font> element with something else like a div. ...

Understanding sessionToken functionality and enabling multiple device logins for a single user simultaneously in Parse

Is there a way to stay logged in as the same user on multiple devices? I have an Android app and a web app and would like to be able to be logged in on both simultaneously. However, when I try to do so, I am receiving an error message 209 stating "invali ...