Skip to content

Instantly share code, notes, and snippets.

@williammalo
Forked from 140bytes/LICENSE.txt
Last active January 26, 2018 21:15
Show Gist options
  • Save williammalo/2193431 to your computer and use it in GitHub Desktop.
Save williammalo/2193431 to your computer and use it in GitHub Desktop.
The cleanest, easiest dom api ever! It will change your life!

I always thought there was a better way to access the dom. This is a tool that allows you to use extremely simple syntax to access dom elements. It makes an object with the name of your choice (I chose "$") that contains a reference to all elements that have an id.

example:

<script> $.foo.innerHTML = "Hello world" </script>

You can even choose to use an object that already exists (I chose "document" because it makes sense)

document.foo.innerHTML = "Hello world"

If you want to live dangerously, you can even make everything global!

foo.innerHTML = "Hello world"

function(
a, //object
d,i //placeholders
){
for(i in d=document.getElementsByTagName('*')) //for every element in the page
a[d[i].id] //make a variable in that object that has the name of the id
=d[i] //set that variable's value to the element
}
function(a,d,i){for(i in d=document.getElementsByTagName('*'))a[d[i].id]=d[i]}
{
"name": "EasyGetElementById",
"description": "The cleanest, easiest dom api ever! It will change your life!",
"keywords": [
"dom",
"id",
"query",
"simple",
"easy"
]
}
<!doctype html>
<span id=foo></span>
<span id=bar></span>
<span id=lorem></span>
<span id=ipsum></span>
<span id=dolor></span>
<span></span>
<script>
easydom = function(a,d,i){for(i in d=document.getElementsByTagName('*'))a[d[i].id]=d[i]}
var $={}
easydom($)
$.foo.innerHTML = "It"
$.bar.innerHTML = "works!"
$.lorem.innerHTML = "amazing"
$.ipsum.innerHTML = "!!!!!!!!"
</script>​
@p01
Copy link

p01 commented Apr 12, 2012

You mixed up b and d in that code snippet, but other than that all good!

I thought about d[i].id||'?' since ? is not a valid ID for HTML elements, that could work OK, but it still feels a bit dirty.

Speaking of dirty, what do you guys think of:

function a(d,i){for(i in d=document.getElementsByTagName('*'))a[d[i].id||'?']=d[i]}

which you use like this:

var $ = function a(d,i){for(i in d=document.getElementsByTagName('*'))a[d[i].id||'?']=d[i]};
$();
$.foo.textContent = 'woohooo!';

What do you guys think of that ?

@williammalo
Copy link
Author

@p01
The problem with both of your edits is the fact that you reset "a" to an empty object. My code has to allow using an object that already exists, for example: "document".
I will take into condideration your "?" idea tho :)

@williammalo
Copy link
Author

@atk and @p01
New version is up! Tell me what you think!
Turns out that the id of an element without an id is always === to ""... so checking if an element has an id isn't important at all.

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