0

I have the following code which I want to create the following links in the HTML if you have opened the http://domain.com/10 URL:

<a href="http://domain.com/5">5</a>
<a href="http://domain.com/6">6</a>
<a href="http://domain.com/7">7</a>
<a href="http://domain.com/8">8</a>
<a href="http://domain.com/9">9</a>
<a href="http://domain.com/10">10</a> // --> You have opened this URL!
<a href="http://domain.com/11">11</a>
<a href="http://domain.com/12">12</a>
<a href="http://domain.com/13">13</a>
<a href="http://domain.com/14">14</a>
<a href="http://domain.com/15">15</a>

Here is the code:

(function() {
  function pagination(number) {
    var url = window.location.href;
    var page = parseInt(url.match(/[^/]+$/));
    var link = '<a href="' + url.replace(/[^/]+$/, '') + (page + number) + '">' + (page + number) + '</a>';
    document.getElementById('pagination').innerHTML = link;
    console.log(link);
  };
  for (var i=-5; i<6; i++) {
    pagination(i);
  };
})();

This code has some problems:

  • console.log(link); will print all of the necessary lines to the console without any problem, but .innerHTML is only appending the last element to the DOM.

  • Somehow I want to hide -5, -4, -3, -2, -1 when you standing at 0 URL.

Ales Maticic
  • 1,895
  • 3
  • 13
  • 27
Lanti
  • 2,299
  • 2
  • 36
  • 69

1 Answers1

1

Assigning something to innerHTML replaces entire element contents with HTML contents. You should append innerHTML instead:

document.getElementById('pagination').innerHTML += link;

To prevent outputting -5, -4, -3, -2, -1 indices, you should probably just check if the number argument is equal to one of these values, e.g.:

function pagination(number) {
    if (number > -6 && number < 0) {
        return;
    }
    //
};
Marat Tanalin
  • 13,927
  • 1
  • 36
  • 52