Unable to access style property, encountering error on separate page

Once again, I'm feeling a bit lost on where to go with this coding issue. It seems quite basic, but I'm struggling to pinpoint the problem. My goal is to hide several IDs, and while it does work, I keep encountering an error: Uncaught TypeError: Cannot read property 'style' of null. This error only shows up on pages where the function isn't present...

function new1()
{
    var news = ["1", "2", "3", "4"];
    for (var i = 0; i < news.length; i++) 
    {
        var s = document.getElementById("news" + news[i]).style.display = "none";
    }
}

Thank you in advance. I can provide the XHTML if necessary. It consists of several divs named news1, news2, etc. My main concern is that this error is interfering with other scripts from functioning properly.

<a onclick="show1()" href="#"><h3>New Song Premiere by Spice Girls</h3></a><div id="news1">
            <p class="news" > <em>"Headlines (Friendship Never Ends)"</em> is the first single from the reformed girl band since 2000 and serves as the official Children In Need track for 2007.</p>

            <p class="news">Geri Halliwell, Victoria Beckham, Melanie Brown, Melanie Chisholm, and Emma Bunton have reunited to promote a new Spice Girls' greatest hits album and an upcoming world tour. <a href="#">Read more ...</a></p></div>
            </div>
        <div id="story2">
            <a onclick="show2()" href="#"><h3>Jay-Z's Defense of Nas' Album Title</h3></a><div id="news2">
            <p class="news">Hip-hop mogul Jay-Z has defended Nas' decision to name his new album <span>N**ger</span>, but he believes the naming was "misguided".</p>

            <p class="news">Jay-Z, real name Shawn Carter, is releasing the LP under his label Island Def Jam Music Group, despite not being a fan of its title. <a href="#">Read more ...</a></p></div>
        </div>
        <div id="story3">
            <a onclick="show3()" href="#"><h3>Amy Winehouse's MTV EMAs Performance Defense</h3></a><div id="new3">
            <p class="news" id="news3">Amy Winehouse has spoken out in defense of her performance at Thursday's MTV European Music Awards, citing exhaustion for her unusual behavior. <a href="#">Read more ...</a></p></div>

Answer №1

While the loop functions correctly for elements in positions 0, 1, and 2, it encounters an issue when trying to access the final element labeled as news4. This leads to a JavaScript error since there is no corresponding DOM element with that specific ID.

To resolve this, simply remove the last entry from your array of IDs:

function new1() { 
    var news = ["1","2","3","4"];
    for (var i = 0; i<news.length; i++) 
    {
        var newsElement = document.getElementById("news"+news[i]);
        if (newsElement != null) 
        { 
            newsElement.style.display = "none";
        }
    }
}

Answer №2

Implementing jQuery can be a great solution for smooth interactions across various browsers:

function hideNews()
{ 
    var newsArray = ["1", "2", "3", "4"];
    for (var j = 0; j < newsArray.length; j++) 
    {
      $('#news' + newsArray[j]).hide();
    }
}

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

What sets apart "config" from "defaults" in Sencha Touch?

As a newcomer to Sencha Touch, I have one simple question that's been on my mind... Can someone explain the distinction between "config" and "defaults" in Sencha Touch? ...

How can I update information based on the chosen option in a select dropdown using Vue?

I have a chart displayed in my user interface that needs to be updated based on the selected time period. By default, the chart displays data from the past year, but when the user selects "Month," it should show data from the past month. <div cla ...

Using Javascript to replace elements with input fields and text areas

I'm currently working on a unique project for my Wordpress blog, where I am developing a custom block editor using JavaScript on the frontend. The goal is to convert all elements from the post content into a series of inputs and textareas. To begin, ...

The npm postinstall script is functional, however, it does not complete successfully and ends

I have encountered an issue while trying to solve a problem with my project. In my package.json file, I have included a postinstall script that connects to a database and calls a function to write data into it. The script seems to be working fine as the da ...

The AjaxPoller object is not defined and causing a TypeError

I have a piece of JavaScript code that handles AJAX requests and updates the DOM: this.AjaxHandler = { sendRequest: sendRequest, fetchDataForElement: fetchDataForElement, handleJsonResponse: handleJsonResponse, checkProgress: checkProgress }; fun ...

PHP: variables malfunctioning post implementation of "if" statement

Recently, I encountered a strange issue while working on a database processor. After processing the login information, the variables containing the data seemed to disappear and any subsequent actions within the "if" statement, which verified the login info ...

Finding the position of the biggest floating point number in the array

What is the best way to find the index of the largest element in an array of floating point numbers? [0.000004619778924223204, 0.8323721355744392, 0.9573732678543363, 1.2476616422122455e-14, 2.846605856163335e-8] Once the index of the largest element is ...

What could be causing setTimeout to trigger ahead of schedule?

I am struggling with a piece of node.js code like this: var start = Date.now(); setTimeout(function() { console.log(Date.now() - start); for (var i = 0; i < 100000; i++) { } }, 1000); setTimeout(function() { console.log(Date.now() - s ...

Mastering the art of transitioning between DIV elements

I am looking to implement a rotating three-card display on click, and have come up with the following code: $('.box1').click(function(){ $('.box1').toggleClass('removeanimate'); $(this).toggleClass('go'); ...

What is the best way to create a taskbar using HTML or Javascript?

I'm currently developing an innovative online operating system and I am in need of a functional taskbar for user convenience. The ideal taskbar would resemble the Windows taskbar, located at the bottom of the screen with various applications easily ac ...

The Angular TypeScript service encounters an undefined issue

Here is an example of my Angular TypeScript Interceptor: export module httpMock_interceptor { export class Interceptor { static $inject: string[] = ['$q']; constructor(public $q: ng.IQService) {} public request(config: any) ...

Node.js API requests often result in undefined responses

As a newcomer to Node.JS, I am currently experimenting with calling a REST API using the GET method. I have utilized the 'request' package available at this link. While the call functions correctly, I encounter an issue when attempting to return ...

Accessing PageController through XmlHttpRequest is not allowed in Shopware 6

I'm encountering an issue when attempting to send a request to my customized StorefrontController on the most recent version of Shopware 6.2.2. The error message I'm receiving is: PageController can't be requested via XmlHttpRequest. I&apos ...

Unlocking the Power of VueJS Mixins in an External JS Library

I'm currently using a 'commonLibrary.js' in my Vue application. One of the functions in this library that I find particularly useful is: var defaultDecimalRounding=3 function formatNumber(number) { if (isNaN(number.value) == tr ...

How to stop parent event propagation in jQuery

I am facing a frustrating issue with my code. Every time I toggle a checkbox, the parent element's click event also triggers. I have experimented with various solutions like: event.stopImmediatePropagation(); event.stopPropagation(); event.preventD ...

Automatically conceal a div once an iframe reaches a specific height

When a user schedules an appointment on our website, it triggers a change in the height of an iframe. I want to automatically hide the section above the iframe once the iframe's height has changed. Currently, I have implemented the following code whic ...

Displaying an STL file at the center of the screen using Three.js positioning

I need assistance with positioning a rendered STL file from Thingiverse in the center of the screen using Three.js and the THREE.STLLoader(). Currently, I have to adjust the rotation properties based on touch coordinates to get the object where I want it. ...

Loop through a list of form names using ng-repeat and send each form name to a JavaScript function when clicked

I have multiple forms within an ng-repeat loop, each with a different name. I need to pass the form data when a button inside the form is clicked. However, when I try to call it like this: checkSaveDisable(updateProductSale_{{productIndex}}) it thro ...

Unable to retrieve API data on local server port 5000. Utilizing a database sourced from a CSV file. Unexpected undefined promise response

I have been struggling for the past few days with a persistent issue. Seeking assistance. Currently working on a project involving a CSV database and creating my own API. It is a small React App Fullstack MERN setup. The specific challenge I am facing is ...

I am puzzled as to why my DataGrid MUI component is not functioning properly

I am taking my first steps with MUI, the MaterialUI React Component library. After following the installation instructions in the documentation, I am now attempting to integrate the DataGrid component into my React project. My goal is to replicate the fir ...