2

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'; 
deceze
  • 510,633
  • 85
  • 743
  • 889
chella
  • 21
  • 1
  • 1
  • 2
  • 4
    Well, it's obvious. `getElementById` returned `null` (because it didn't find any element with that ID). – Šime Vidas Jul 18 '11 at 13:37
  • You should have a dedicated function for setting classes (or use a library). – Šime Vidas Jul 18 '11 at 13:43
  • @Šime Vidas Why? This may be a one-off usage not requiring a function. And not every JS problem requires a 100k library to solve. – Michael Berkowski Jul 18 '11 at 13:45
  • @Michael Because the OP has to perform that task (setting a class-name) multiple times. It's called the [DRY principle](http://en.wikipedia.org/wiki/Don%27t_repeat_yourself) – Šime Vidas Jul 18 '11 at 14:06
  • @Šime Vidas But we don't know the context of this code. And since it includes `this.` it's likely that it already exists inside a function. – Michael Berkowski Jul 18 '11 at 14:11
  • @Michael Yes, the above code is most certainly inside a function (probably an event handler), but I fail to see why that is relevant. The point I'm making is that setting a class-name based on an ID string is a complex task (it requires multiple statements). Therefore, if that task has to be performed multiple times, in order to avoid redundancy, it (that task) should be isolated into a dedicated function. – Šime Vidas Jul 18 '11 at 14:18

2 Answers2

3

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.

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
0

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.

Nicolae Albu
  • 1,235
  • 6
  • 6