I keep encountering the error message "Cannot access the 'style' property of null" despite having already included the 'position: absolute;'

As a coding beginner, I've decided to delve into the world of HTML, CSS, and Javascript by creating a racing game for the browser. However, I seem to have hit a roadblock with error messages popping up whenever I try to control the car:

Cannot read property 'style' of null

Below is my code snippet:

var car = document.getElementById('car');
var container = document.getElementsByClassName('container');


var carLeft = 0;

function anim(e) {
  if (e.keyCode==87) {
    //W

  }

    if (e.keyCode==65) {
      //A
      carLeft+=2;
      car.style.left = carLeft + 'px';
  }

    if (e.keyCode==83) {
      //S

  }

    if (e.keyCode==68) {
      //D
      carLeft-=2;
      car.style.left = carLeft + 'px';
  }
}

document.onkeydown =anim;

And here's my CSS styling:

#car {
    background-color: blue;
    height: 10px;
    width: 20px;
    z-index: 10;
    position: absolute;
    left: 0;

}

Answer №1

The car variable stores a collection of objects with the class name "container".

var car = document.getElementById('car');
var container = document.getElementsByClassName('container')[0];//using this method


var carLeft = 0;

function animateCar(e) {
  if (e.keyCode==87) {
    //W

  }

    if (e.keyCode==65) {
      //A
      carLeft+=2;
      car.style.left = carLeft + 'px';
  }

    if (e.keyCode==83) {
      //S

  }

    if (e.keyCode==68) {
      //D
      carLeft-=2;
      car.style.left = carLeft + 'px';
  }
}

document.onkeydown = animateCar;

Answer №2

Consider using querySelector for a more efficient solution to the issues you are experiencing.

var car = document.querySelector('#car');
var container = document.querySelector('.container');


var carLeft = 0;

function anim(e) {
  if (e.keyCode==87) {
    //W

  }

    if (e.keyCode==65) {
      //A
      carLeft+=2;
      car.style.left = carLeft + 'px';
  }

    if (e.keyCode==83) {
      //S

  }

    if (e.keyCode==68) {
      //D
      carLeft-=2;
      car.style.left = carLeft + 'px';
  }
}

document.onkeydown = anim;
#car {
    background-color: blue;
    height: 10px;
    width: 20px;
    z-index: 10;
    position: absolute;
    left: 0;

}
<div class="container">
  <p id="car">
    Change the text here lorem ipsum dolor
  </p>
</div>

Please provide your html version and feedback on whether this answer was helpful so I can make improvements as needed.

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

Modify parent element's opacity exclusively

I have thoroughly searched all the questions on StackOverflow and this is not a repeat inquiry. I need assistance with a specific issue on the website . In the "Recent Projects" section, when hovering over the image, only the background <article> ele ...

There seems to be an issue with my JavaScript module as it is displaying an error of "

Within my js file, I have the following code snippet: ; var tracker = (function () { var _track = function(userId, atts) { alert(userId); }; return { track: function (userId, atts) { _track(userId, atts); ...

Synchronous CORS XHR encounters issues with 302 redirect, while asynchronous function successfully redirects

Why does Firefox seem to be the only browser that doesn't throw an error when performing a synchronous request? Any insights on this peculiar behavior? // Ensure your JS console is open when running this script var url = '//api.soundcloud.com/ ...

Is it possible to use Three.js as the backdrop for a website design?

For a new project on my website, I am considering using three.js for an interactive experiment. My idea is to take an existing experiment that I already have the code for and integrate it as a dynamic background for my site. Does anyone have experience wi ...

Reverse the action if the user selects "cancel" when asked to confirm using the `confirm()` function

I created a handy feature that allows you to drag items from a list to a trash can for deletion. When you click "ok", the item is successfully removed as intended. However, if you hit "cancel" on the confirmation popup, the item still goes into the trash ...

Using Jade language in a standard web application without the need for Node.js

Can Jade be utilized in a traditional web application without reliance on Node.js? This question might seem unconventional considering Jade is built for Node, but I'm curious to know if its functionality can extend beyond the Node environment. ...

The request to remove the product from the server at URL http://localhost:8000/product/[object%20Object] encountered an internal server

I'm having trouble setting up the AJAX delete method. I keep getting a 500 internal server error and despite following tutorials, I remain frustrated. Can someone please help me correct my code? This is using Laravel 5.8 and jQuery 3.3. <section ...

Error: selenium web driver java cannot locate tinyMCE

driver.switchTo().frame("tinymce_iframe"); String script="var editor=tinyMCE.get('tinymce_textarea');"; JavascriptExecutor js=(JavascriptExecutor) driver; js.executeScript(script); I'm encountering a WebDriverException while try ...

Unable to align text in the center

I'm having an issue with aligning my text perfectly in the center. How can I resolve this while still maintaining the ability to adjust it vertically? <center> <div class="home-text"> <div class="col-md-6 col-md-offset-3"&g ...

Utilize JavaScript to extract an image from an external URL by specifying its attributes (id, class)

Is it possible to fetch an image from an external website by using its CSS id or class in conjunction with JavaScript/jQuery's get methods? If so, could someone provide guidance on how to achieve this task? ...

Preventing the insertion of a line break when using Shift + Enter in Vuejs

Whenever I use a textarea to enter text, I find that I have to press Shift + Enter every time to send the text. However, upon sending, it adds /n at the end. I prefer using the Enter key for newline instead of submitting the form. Example: hello => ...

How can I create a responsive input group with automatic width using Bootstrap 3.1?

I am having trouble with the layout of my two floating divs. The first div contains buttons and the second div contains an input-group. However, the input-group is moving down a line instead of utilizing the available space. Here is a link for reference: ...

Dynamic cell loading in Vue using Vuetify's datatable functionality

<template> <v-data-table :headers="headers" :items="records" :items-per-page="5" show-select loading item-key="id" class="elevation-1" > <template v-slot:top> <div> <table-tabs> ...

Access information from a pair of tables in MYSQL

I want to create a simple platform for discussions where users can log in and post their discussions. The main goal is to display these discussions on the homepage. To achieve this, I first fetch the discussion data (topic, category, username, etc) from t ...

Why is the JS Component failing to appear on the page?

My component is not rendering on the page. Despite no errors or warnings, I have logged the gameData value and confirmed that all data is correct. Below is the function being exported: export default function AllGameDeals( gameData ){ const dealArr = ...

Responsive Font Sizing in React Native

Does React Native automatically adjust font size based on screen size? If I set the fontSize to 10 for a Text component, will it resize according to different phone sizes? If not, what is the best way to make fonts responsive in React Native? ...

Crafting a see-through circular prism

Is there a way to create a transparent cylinder in Three.js? I've tried using different settings like transparent or opacity but haven't had much success. Should I load a dummy texture with an alpha channel, or is there a simpler solution? mater ...

Guide to showing the username on the page post-login

My MongoDB database is filled with user information. I'm looking to create a feature on the webpage that displays "Logged in as username here" at the top once users log in. My CSS skills are strong, but when it comes to JavaScript, I'm struggling ...

Show the day of the week

I'm seeking a solution to display the upcoming Friday of each week within Wordpress. We were able to achieve this in the past using the code below on non-Wordpress platforms, but it seems outdated and no longer functional. For example: This week&apos ...

Incorporating text onto an HTML webpage

Context: My program reads a file and displays it on an HTML page. The code below utilizes regex to extract errors from the file. Instead of using console.log for debugging, is there a way to display the results on the HTML page? When attempting: document ...