What could be the reason for encountering the error message "Attempting to access an undefined HTML property"?

I've been working on a simple counter to practice closures in JavaScript, and I'm struggling with an error that I can't seem to solve. I thought assigning the variable elem to the id of canv would do the trick, but clearly something isn't right. Can anyone point out what's going wrong here?

This is my HTML:

<body>
  <div id="canv">

  </div>
</body>

This is my JavaScript:

function setup(delay) {
  var el = document.getElementById('canv');

  counterFn(el, delay);
}

function counterFn(el, delay) {
  var counter = 0;

  setInterval(getTime, delay);

  function getTime(el) {
    el.innerHTML(counter);
    counter++;
  }
}

setup(500);

It all seems quite basic, yet I can't pinpoint where I'm going astray.

Check out my JSFiddle for a clearer picture: https://jsfiddle.net/8sjaqdrh/2/

Answer №1

The issue that triggered the error is due to the fact that el is not defined within the scope of getTime.

In the parent scope of getTime, which is counterFn, el is defined because it was assigned a value when called in counterFn(el, delay) inside the setup function as

el = document.getElementById('canv')
.

However, within the scope of getTime, no value was provided for el. As a result, el becomes undefined.

Another issue in the code is the improper usage of innerHTML.

To fix this, simply remove the parameter from function getTime(el){... and make it function getTime(){....

Additionally, note that innerHTML is not a function and should not be called like innerHTML(counter).

Instead, assign a value directly to it using innerHTML = counter.

function setup(delay) {
  var el = document.getElementById('canv');

  counterFn(el, delay);
}

function counterFn(el, delay) {
  var counter = 0;

  setInterval(getTime, delay);

  // Corrected code:
  function getTime() {
    el.innerHTML = counter;
    counter++;
  }
  
  /* Your code
  function getTime(el){
    el.innerHTML(counter);
    counter++;
  }
  */
}

setup(500);
<div id="canv"></div>

Answer №2

Ensuring that the canvas element exists in the DOM before trying to access it is crucial here. To prevent any errors, make sure to wrap your code within a window.onload event.

In the snippet below:

setInterval(getTime, delay);

You've defined getTime as expecting a parameter but failed to pass one. Instead, try:

setInterval(function(){ getTime(el); }, wait);

Lastly, change el.innerHTML(counter); to el.innerHTML = counter;.

Here's a functioning Fiddle for reference

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

Issue with displaying Bootstrap column accurately

My attempt to create a row with 3 columns is not working as expected. The columns are displaying as rows instead. <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8> &l ...

Create a function that multiplies every element in an array by 2

This example involves some JavaScript code. Currently, I have written the following: var double = function (array) { var newArray = []; for(var i = 0; i<array.length; i++) { newArray.push(array[i]); newArray.push(array[i]); ...

Conceal the scroll bar while the page preloader is active

Is there a way to hide the scroll bar while the preloader is loading on a webpage? I want to prevent users from scrolling until the preloader disappears. I have tried using CSS and setting the body overflow to hidden, but it's not working as expected. ...

Guide on integrating web api on android with javascript, jquery, and jsonp

I am attempting to create a button in my Android application that, when clicked, retrieves information from a web API and displays the results on my screen. Here is the code that performs the necessary tasks, but I need to integrate it into my Android pag ...

Crafting a robust and secure password using Yup and Formik while receiving personalized error notifications

My Password Validation Dilemma I'm in the process of developing a password field that can assess the strength of the input provided. In a different response, I came across a regex that I could utilize to validate whether the input meets specific crit ...

Display React component when clicked

As a newcomer to the world of React, I find myself intrigued by its potential. However, I am still in the process of grasping the fundamental concepts and would greatly appreciate any explanations provided. My goal is to display an 'About' compo ...

Is there a way to delete objects that are added dynamically to an array using a specific button linked to each object?

I am currently using Angular to develop a shopping list application. To facilitate testing, I have set up two pre-made lists with two and three pre-defined items each. However, the goal is for users to dynamically add both items and lists themselves in the ...

Performing calculations in each row of a dataframe using JavaScript

As someone who is just starting out with nodejs, I am interested in utilizing the dataframe-js library to iterate through rows and calculate the difference between each cell and the previous row. const columns = ["x","y","gap"]; const df= new DataFram ...

What do you believe to be superior: Vue UI design?

Scenario: Application managing multiple user roles. A view with extensive conditional rendering in the template. a) Is it preferable to have numerous conditional statements in a single view's template? b) Should separate views be created for each ro ...

use ajax to post saved data to a WebAPI in php

I have successfully implemented the code to save data in a custom table using Ajax. Now, I need to figure out how to send this data to an asp.Net API using js/jQuery. How can I achieve this? Below is my HTML form and JS code: <div id="inline1" class= ...

What is the best way to connect this image and comments div using only CSS?

I'm trying to ensure the comments div is the same height as the image above so they can be aligned side by side. Below is my current code: <div class="main_image_wrapper"> <img class="main_image" src="*dynamic generated image*" style="ma ...

Encountering issues with posting data on a straightforward Node.js form using routes

I'm having trouble getting a simple form to post within my NodeJS/ExpressJS app. The code in my app.js file (referred to as server.js) is as follows: var express = require('express'); var fs = require('fs'); var path = require(&a ...

Avoid Reselecting Dropdown Choices in PowerApps Model-Driven Apps

Currently, I am working on a PowerApps project that involves multiple dropdown lists (option sets) where users should only be able to select each team once. I am striving to prevent users from reselecting teams that have already been chosen but facing some ...

Looking for a node.js IDE on OS X that can display JSON objects similar to how they appear in the console of Chrome or Firefox?

While using Google Chrome, I noticed that when I console.log(object), a detailed view of the object is displayed in the console instead of just a string representation. This feature is incredibly useful. Unfortunately, when running node.js scripts on my ...

When using jQuery Ajax, only pass the query string if it is defined and not empty

Using jquery and ajax to communicate with a CMS API, I am constructing a query string to fetch data: region = typeof region !== 'undefined' ? 'region='+region : ''; centre = typeof centre !== 'undefined' ? 'cen ...

In JavaScript, not all elements are removed in a single iteration, even if the condition is consistently met

I'm currently attempting to compare two arrays containing multiple objects and remove elements based on a condition. To my surprise, while testing in Chrome's console, I noticed that the first array (arr1) is not being emptied even though I am us ...

Creating a custom video to use as the favicon for my website

Imagine this: With the help of this plugin, you can have a video playing as your site's favicon using the following code snippet: var favicon=new Favico(); var video=document.getElementById('videoId'); favicon.video(video); //stop favicon.v ...

Establish a table containing rows derived from an object

I am currently dealing with a challenge in creating a table that contains an array of nested objects. The array I have follows this schema: array = [ { id: 'Column1', rows: { row1: 'A', row2 ...

Delay Time for Closing Sub Menus When Multiple Dropdowns are Opened

My issue involves a multi-level drop-down menu that is solely constructed using CSS. The problem I am facing is that there is a delay of one second before the drop-down closes when the mouse is moved away. This delay causes multiple drop-down menus to stac ...

Material UI - Array of Chips

I have been working on creating a ReactJS component that displays an array of chips with unique styling for each one. To achieve this, I created individual makeStyles classes for the chips. However, I encountered difficulties in dynamically changing the cl ...