Last active
September 17, 2023 14:54
-
-
Save MiffOttah/6b5e5b53efec58cc16e6abd3e11f6135 to your computer and use it in GitHub Desktop.
createChild and live - Bringing Vanilla Javscript close to jQuery's convinence.
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
/* | |
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE | |
Version 2, December 2004 | |
Copyright (C) 2004 Sam Hocevar <sam@hocevar.net> | |
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. | |
*/ | |
// This function is exctremely useful | |
Element.prototype.createChild = function (type, attributes, text) { | |
const c = document.createElement(type); | |
if (attributes) { | |
for (let i in attributes) c.setAttribute(i, attributes[i]); | |
} | |
if (text) { | |
c.textContent = text; | |
} | |
this.appendChild(c); | |
return c; | |
}; |
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
/* | |
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE | |
Version 2, December 2004 | |
Copyright (C) 2004 Sam Hocevar <sam@hocevar.net> | |
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. | |
*/ | |
HTMLElement.prototype.live = function (event, selector, handler) { | |
const parent = this; | |
parent.addEventListener(event, function (...eventArguments) { | |
let n = eventArguments[0].target; | |
while (n) { | |
if (n.matches(selector)) { | |
return handler.apply(n, eventArguments); | |
} | |
if (n === parent) { | |
return; | |
} else { | |
n = n.parentElement; | |
} | |
} | |
}, true); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment