Skip to content

Instantly share code, notes, and snippets.

@mikefowler
Created September 28, 2012 17:48
Show Gist options
  • Save mikefowler/3801240 to your computer and use it in GitHub Desktop.
Save mikefowler/3801240 to your computer and use it in GitHub Desktop.
Constraining index when selecting DOM elements.
<!--
This is a simple way to constrain an index to a range. A good use case for this is
selecting DOM elements and then getting the element on a given index in that selection.
The code in getIndexInSelection() will constrain the index to the range of elements available,
choosing either the highest or lowest index if the requested index is out of range.
-->
<div id="container">
<section>...</section>
<section>...</section>
<section>...</section>
<section>...</section>
<section>...</section>
<section>...</section>
<section>...</section>
</div>
var elements = document.querySelectorAll('#container section');
function getIndexInSelection(index) {
return Math.max(Math.min(index, elements.length - 1), 0);
}
getIndexInSelection(10); // Returns: 6
getIndexInSelection(8); // Returns: 6
getIndexInSelection(4); // Returns: 4
getIndexInSelection(-2); // Returns: 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment