[Solved] Uncaught TypeError: Cannot set property ‘className’ of null

I am using js file for paginate a table. It occurs an error while I am trying to click on next page button. It just show the error like this “Uncaught TypeError: Cannot set property ‘className’ of null”.

Here is my code:

    var oldPageAnchor = document.getElementById('pg'+this.currentPage);
    oldPageAnchor.className = 'pg-normal';
    this.currentPage = pageNumber;
    var newPageAnchor = document.getElementById('pg'+this.currentPage);
    newPageAnchor.className = 'pg-selected'; 
Enquirer: chella

||

Solution #1:

It fails because there is no DOM element with the id 'pg'+this.currentPage. If this is normal behavior, then you can just wrap the className call in an if block:

var oldPageAnchor = document.getElementById('pg'+this.currentPage);
if (oldPageAnchor) {
   oldPageAnchor.className = 'pg-normal';
}

Otherwise, you’ll need to post more code to show us where this.currentPage is set in JavaScript, and the HTML on which it is acting.

Respondent: Michael Berkowski

Solution #2:

oldPageAnchor or newPageAnchor is null because the element with your specified ID is not found. Check that this.currentPage has your desired value AND that the elements that you are trying to find are on the HTML page you’re on.

Respondent: Nicolae Albu

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.