Skip to content

Instantly share code, notes, and snippets.

@evitolins
Last active December 29, 2015 07:39
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 evitolins/7637443 to your computer and use it in GitHub Desktop.
Save evitolins/7637443 to your computer and use it in GitHub Desktop.
A simple function to simplify the act of gathering DOM elements for manipulation.

Example Usage

// Gather needed DOM elements
var dom = getElementsByIds('myContainer','mySlider','myBtn','myBtn.a','myBtn-1');

// Manipulate some gathered objects
dom.myContainer.style.backgroundColor = "red";
dom.mySlider.value = 20;
dom.myBtn.addEventListener("click", function(){ alert("button pushed"); });

// More complex ids need special care...
dom['myBtn.a'].addEventListener("click", function(){ alert("button pushed"); });
dom['myBtn-1'].addEventListener("click", function(){ alert("button pushed"); });

Reference

Found this one by searching "getElementsByIds". Probably should have searched for a solution more carefully prior to writing one. Well, at least I learned to improve my script by cloning the array properly, as done in the following suggestion.

/**
* Returns an object of elements, from a given list of ids (ev)
* @return {object} Object containing any matching element ids, assigning
* the id as the key
*/
var getElementsByIds = function() { "use strict";
var r = {},
a = [].slice.call(arguments),
e,id,i;
for (i=0; i<a.length; i++) {
id = a[i];
e = document.getElementById(id);
if (e) {
r[id] = e;
}
}
return r;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment