Skip to content

Instantly share code, notes, and snippets.

@av01d
Last active May 27, 2024 13:43
Show Gist options
  • Save av01d/424add0af76ecdd49bdf3af337ba466c to your computer and use it in GitHub Desktop.
Save av01d/424add0af76ecdd49bdf3af337ba466c to your computer and use it in GitHub Desktop.
Javascript: tiny jQuery
// Select single element
const $ = (e, parent = document) => parent.querySelector(e);
// Select multiple elements
const $$ = (e, parent = document) => Array.from(parent.querySelectorAll(e));
// Create element
const cE = (tagName, props) => {
const el = document.createElement(tagName);
for (let prop of ['id','name','value','className','type','href','method','action']) {
// Direct properties
(prop in props) && (el[prop] = props[prop]);
}
('css' in props) && (el.style.cssText = props.css);
('text' in props) && (el.textContent = props.text);
('html' in props) && (el.innerHTML = props.html);
('onclick' in props) && (el.addEventListener('click', props.onclick));
return el;
}
@av01d
Copy link
Author

av01d commented May 22, 2024

Usage example:

// Select single element
const el = $('#myDiv');

// Select (and loop) multiple elements
for (let el of $$('.myClass')) {
   el.innerHTML = 'something';
}

// Create elements
const div1 = cE('div', {className:'myClassName'});
const div2 = cE('div', {css:'display:flex; align-items:center; justify-content:space-between'}, html:'My <b>Content</b>');
const ipt = cE('input', {name:'test', type:'text', value:'my value'});
const btn = cE('button', {className:'btn', text:'Click me, onclick:() => {
  alert('Click!');
});
document.body.append(cE('form', {method:'post', action:'download.php'});

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