Skip to content

Instantly share code, notes, and snippets.

@duncancola
Forked from 140bytes/LICENSE.txt
Created November 22, 2012 10:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duncancola/4130329 to your computer and use it in GitHub Desktop.
Save duncancola/4130329 to your computer and use it in GitHub Desktop.
Generate an ID for a DOM element which is sure to be unique

genUID

Create a string which will be a suitable ID for an element. The ID will be unique (not currently in use by any other DOM element).

function (
p // an optional prefix for the id
)
{
var c = 0, // c is the counter to add as a unique suffix to the end of the optional prefix string
i; // i is the unique id string
p = (typeof p==="string")?p:""; // if p is a string it can be used as the prefix, otherwise p is set to the empty string
do {
i = p + c++; // the id is set to the prefix joined with the incremented counter
} while (document.getElementById(i)!==null); // if an element has been found with this ID we must loop again, incrementing the counter until a unique ID is created
return i; // return the id string
}
function (p) {var c = 0,i;p = (typeof p==="string")?p:"";do{i=p+c++;}while(document.getElementById(i)!==null);return i;}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 DUNCAN GRANT <http://www.duncangrant.co.uk>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "generateUniqueDOMIDs",
"description": "Return a string which is a safe (not currently in use) ID for a DOM element on the page.",
"keywords": [
"DOM",
"unique",
"ID"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div>Expected value: <b>undefined</b></div>
<div id="inuse"></div>
<div id="inuse1"></div>
<div id="inuse2"></div>
<div>Actual value: <b id="ret"></b></div>
<script>
// write a small example that shows off the API for your example
// and tests it in one fell swoop.
var genUID = function(p){var c = 0,i;p = (typeof p==="string")?p:"";do{i=p+c++;}while(document.getElementById(i)!==null);return i;}
document.getElementById( "ret" ).innerHTML = genUID("inuse");
</script>
@atk
Copy link

atk commented Nov 23, 2012

''+p===p is shorter than typeof p==="string"; Also: use "for" loop to golf that further down.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment