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>​
@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