Created
September 28, 2012 17:48
-
-
Save mikefowler/3801240 to your computer and use it in GitHub Desktop.
Constraining index when selecting DOM elements.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- | |
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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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