What could be causing the console to show the error message "TypeError: newIndustry is null"?

Can anyone help me identify the issue I am facing with this particular line...

    newIndustry.innerHTML = industryNews[generateRandomNumber()-1]
}

I am using this JavaScript code to insert text into a heading element with #industryNews:

var industryNews = [];
industryNews[0] = "Lorem ipsum dolor <strong>sit</strong> amet, consectetur adipisicing elit. Optio, ut, maxime, eum, fugit dolor nulla cupiditate beatae sapiente dignissimos accusamus cumque fuga alias accusantium praesentium nisi placeat quam ad eius.";
industryNews[1] = "Lorem ipsum dolor <strong>sit</strong> amet, consectetur adipisicing elit. Provident, consequuntur, officia veritatis molestias odio nobis minima iste id tenetur possimus magni nisi error enim minus aperiam? Minus, iure delectus cumque.";
industryNews[2] = "Lorem ipsum dolor <strong>sit</strong> amet, consectetur adipisicing elit. Sint, in, qui voluptatibus voluptas inventore recusandae non quos adipisci dolor beatae dolore saepe quaerat exercitationem dolores delectus quo pariatur. Quae, quidem.";
industryNews[3] = "Lorem ipsum dolor <strong>sit</strong> amet, consectetur adipisicing elit. Assumenda, sed, laborum, quisquam rerum quo non aspernatur necessitatibus soluta id debitis impedit corporis magnam praesentium ab odit dicta aperiam autem consequuntur!";

var newIndustry = document.getElementById("industryNews");

// function to generate a random number between 1 and 4
function generateRandomNumber(){
    return Math.floor(Math.random()*(4)+1);
}

function updateindustryNews () {
    newIndustry.innerHTML = industryNews[generateRandomNumber()-1]
}

updateindustryNews();

setInterval(updateindustryNews,4000);

Answer №1

When trying to use document.getElementById() on a page, it's important to remember that HTML needs to exist first. This means your script tag should be placed at the bottom of the body or within the head section. If placed in the head, you'll need to utilize the onload property which belongs to the implicit window.

On a side note, while unrelated to your issue, it's worth mentioning that Math.random() generates a number between 0 and .9 (excluding 1). So, the formula:

function generateRandomNumber(){
  return Math.floor(Math.random()*(4)+1);
}

is not optimal as Math.floor(0.99999*4+1) still equals 4. It would be better written as:

function generateRandomNumber(){
  return Math.floor(Math.random()*4);
}

This way, you won't have to subtract 1 from the result.

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

The functionality of AJAX is hindered in the browser when attempting to fetch data from a URL

Lately, I've been encountering a strange issue when trying to fetch data from a URL. $.ajax({ url: 'URLHERE', dataType: 'html', success: function(data) { //function 2 var xml = $.parseXML(data) $(xml).find('StopLoca ...

Guide to organizing a program for adding items to a list using Backbone.Marionette

One thing that continues to confuse me about Marionette is how to structure it efficiently. Let's consider a simple interface for displaying a list of comments and adding a new comment. I am currently structuring this using a CommentApp as shown belo ...

The div element is supposed to only be visible when the user scrolls down and then back up, rather than when the

Looking for some help with a Javascript issue on my website (http://www.pjsmusic.com). I need a div of 200px to appear when the user scrolls down 40px. I have tried using the following Javascript code: $(document).scroll(function() { $('#jerkBox& ...

Difficulty arises when Jest tests struggle to interpret basic HTML tags within a React Component

When running test runs, issues arise when using standard HTML tags with Jest. My setup includes Babel, Webpack, Jest, and React Testing Library. To enable jest, I have installed a number of packages: "@babel/plugin-proposal-class-properties": "7.8.3", "@ ...

Tab switch or application switch?

Is there a way to distinguish between different browser events in the following scenarios? When the user clicks on another tab within the same browser, causing my tab to be hidden and should pause. When they switch to another application, with my tab ...

Revise if a specific file is not being called by AJAX

I am currently utilizing a routing library known as Grapnel.js. It requires URLs in the format of index.php#something/something, which is why I am using htaccess to rewrite /something/something to match that structure. However, I would like the flexibility ...

BackboneJS struggles to redirect to .fail when an API request exceeds the timeout

I'm a newbie to backbone and I've come across some interesting code that adds Deferred to enable the use of promises. Take a look at the snippet below: getPatientInfo: function fetch(options) { var deferred = $.Deferred(); Backbone.Model.p ...

Understanding the status of HTTP requests or observing the updates of observables in Angular2/Typescript is essential

I've been working on an Angular2 and Typescript application where I'm utilizing Angular2's HTTP methods to retrieve data from a database within a service. The service is triggered inside a component's onInit() function and I'm able ...

Learn how to dynamically highlight a table row when any changes are made to it using jQuery

Is there a way to automatically highlight the current table row when any input text or image is changed within that specific row using jQuery? In the given code snippet below, with two rows provided, how can one of the rows be highlighted upon modifying ...

Execution of scripts upon completion of document loading via AJAX

When loading a portion of HTML through AJAX, my expectation was that the JavaScript code inside would not run because it is dependent on the DOM being ready. However, to my surprise, the code within document.ready is still executing. I have even placed a ...

Eliminate repeat entries in MongoDB database

Within our MongoDB collection, we have identified duplicate revisions pertaining to the same transaction. Our goal is to clean up this collection by retaining only the most recent revision for each transaction. I have devised a script that successfully re ...

Instructions for deactivating a drop-down list using radio buttons in JavaScript

I am working on a project where I have 3 radio buttons and 3 different combo boxes in my HTML. I want to use JavaScript to enable/disable the combo boxes based on which radio button is selected. For example, when the G1 radio button is clicked, I want on ...

Pictures are not showing up in the gallery after they have been saved

if (action.equals("saveToGallery")) { JSONObject obj = args.getJSONObject(0); String imageSource = obj.has("imageSrc") ? obj.getString("imageSrc") : null; String imageName = obj.has(" ...

Generating a JavaScript variable linked to a Rails Active Record relationship

I'm trying to implement an active record association in the DOM, but I'm encountering some difficulties. Here is my editor class: .editing .row .col-sm-3 .col-sm-8 .text-left #font-20 .title-font . ...

Suggestions for this screenplay

I am completely new to the world of coding and computer languages, and I could use some guidance on how to utilize this script for a flash sale. setInterval(function() { var m = Math.floor((new Date).getTime()/1000); if(m == '1476693000000& ...

Unable to retrieve the index value from the content of a looped data attribute

Here is the code snippet I'm working on. To enhance the details, I iterate through each data attribute of the clicked element, retrieve the content, split it by "%" and then loop through each split content. My goal is to alert the content at index &ap ...

Ways to prevent decreasing the value below zero in ReactJS?

I have created two buttons, one for increasing and another for decreasing a counter value. However, when I click on the minus button, it should not display negative values. But in my case, when I click on the minus button (initially at zero), it shows -1, ...

Looking for a way to identify when a DOM element is resized as a result of web fonts loading asynchronously?

Within this div element lies text styled with a custom font via CSS's @font-face attribute. The issue arises when the font hasn't loaded yet, causing a delay in updating the font style of the text within the div. As a result, taking measurements ...

Ensuring the accuracy of a single field within a form containing multiple fields is made possible through the utilization of

I am facing an issue with my emailValidation method. Even though I want it to run when this.$refs.editUserForm.validate('email') returns true, it always seems to return false, especially when a valid email like <a href="/cdn-cgi/l/email-protec ...

Checking and contrasting dates within Javascript

Looking to compare two dates with different formats: a) Date1 - 01 Feb 2019 b) Date2 - 2/3/2017 It's important to account for invalid dates and ensure that Date1 is greater than Date2. function CompareAndValidateDates() { var Date1 ="01 Feb 20 ...