3

I've been building a table using AJAX to get the table's contents. To navigate through its pages I used bootstrap's pagination component. The pagination is also built with js and the elements are inserted in this loop:

for (i = 1; i <= pageCount; i++) {
  var li = $("<li>");
  li.append($("<a>").attr("href", "#").data("page", i).html(i));
  li.appendTo("ul.pagination");
} // end for (i = 1; i <= pageCount; i++)

If the user navigates to another page the active element should be switched to the corresponding one.

$("ul.pagination li.active").removeClass("active"); // works fine

Unfortunately using $(this) in the 'click' handler is not an option because I also need this elsewhere.
So I altered the solution I found here: https://stackoverflow.com/a/4191718/6087532
This didn't work for me (I tried a few variations):

$('ul.pagination li a[data-page="' + page + '"]').parent().addClass("active");

When I tried to inspect the resulting element(s) in the console I always didn't get any results.

I found a workaround using .each:

$('ul.pagination li a').each(function(index, element) {
  if ($(this).data("page") == page) {
    $(this).parent().addClass("active");
  }
});

But this is seriously bugging me because a) this solution is not very elegant and probably slower and b) I cannot figure out what I did wrong.

Community
  • 1
  • 1
djsnape
  • 96
  • 6

1 Answers1

2

jQuery .data() and HTML attribute data-*** is not the same.

So if you want to use this:

$('ul.pagination li a[data-page="' + page + '"]').parent().addClass("active");

You have to change your loop to this:

for (i = 1; i <= pageCount; i++) {
  var li = $("<li>");
  li.append($("<a>").attr("href", "#").attr("data-page", i).html(i));
  li.appendTo("ul.pagination");
} // end for (i = 1; i <= pageCount; i++)
Undefitied
  • 747
  • 5
  • 14
  • Thanks for clarifying this. I thought that because the values stored in data-*** are accessible through .data() this would work in both directions. – djsnape Mar 20 '16 at 00:44