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.