So, I have an array of tabs in an overflow auto container (the tabs const) and I want to filter them to get the last visible one. My idea is to take the x value of the container (overflowWrapperRight) and get the tab whose left side is less than that value and whose right side is greater than that value. The problem is that I get the message that my filter is not a function. Maybe it´s a silly mistake, but I'm stuck.
const overflowWrapperRight =
wrapper.getBoundingClientRect().x + wrapper.getBoundingClientRect().width;
const current = wrapper.scrollLeft;
const tabs = document.querySelectorAll('#tablistPanel .singleTab');
const lastVisibleTab = tabs.filter(
tab =>
tab.getBoundingClientRect().left < overflowWrapperRight &&
tab.getBoundingClientRect().right > overflowWrapperRight
);
I should get the single tab which matches that criteria.
答案 0 :(得分:-1)
That's because Element#querySelectorAll
returns a NodeList
rather than an array.
You can easily convert a nodelist into an array using spreading, like so:
const overflowWrapperRight =
wrapper.getBoundingClientRect().x + wrapper.getBoundingClientRect().width;
const current = wrapper.scrollLeft;
const tabs = document.querySelectorAll('#tablistPanel .singleTab');
const lastVisibleTab = [...tabs].filter(
tab =>
tab.getBoundingClientRect().left < overflowWrapperRight &&
tab.getBoundingClientRect().right > overflowWrapperRight
);
You could also achieve the same using Array.from
like so:
const lastVisibleTab = Array.from(tabs).filter(
tab =>
tab.getBoundingClientRect().left < overflowWrapperRight &&
tab.getBoundingClientRect().right > overflowWrapperRight
);
Finally, there's is the ES5 compatible way using Array#slice
, like so:
const lastVisibleTab = Array.prototype.slice.call(tabs).filter(
tab =>
tab.getBoundingClientRect().left < overflowWrapperRight &&
tab.getBoundingClientRect().right > overflowWrapperRight
);