Какие доводы против того чтобы аттрибуты передавались вторым аргументом?
'use strict';
const $ = (selector, node = document) => node.querySelector(selector);
const $$ = (selector, node = document) => [...node.querySelectorAll(selector)];
function createElement(tag, content, attrs) {
const elem = document.createElement(tag);
if (Object.prototype.toString.call(content) === '[object Object]') {
[content, attrs] = [attrs, content];
}
if (attrs !== null && typeof attrs !== 'undefined') {
for (let [k, v] of Object.entries(attrs)) {
if (k.startsWith('on')) {
elem.addEventListener(k.slice(2), v);
} else {
elem.setAttribute(k, v);
}
}
}
if (content !== null && typeof content !== 'undefined') {
if (Array.isArray(content)) {
for (let v of content) {
addContent(elem, v);
}
} else {
addContent(elem, content);
}
}
return elem;
}
function addContent(element, content) {
if (content instanceof HTMLElement || content instanceof Text) {
element.appendChild(content);
} else {
element.appendChild(new Text(content));
}
}
const htmlTags = 'a|abbr|address|area|article|aside|audio|b|base|bdi|bdo|blockquote|body|br|button|canvas|caption|cite|code|col|colgroup|data|datalist|dd|del|details|dfn|dialog|div|dl|dt|em|embed|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|head|header|hgroup|hr|html|i|iframe|img|input|ins|kbd|keygen|label|legend|li|link|main|map|mark|menu|menuitem|meta|meter|nav|noscript|object|ol|optgroup|option|output|p|param|pre|progress|q|rb|rp|rt|rtc|ruby|s|samp|script|section|select|small|source|span|strong|style|sub|summary|sup|table|tbody|td|template|textarea|tfoot|th|thead|time|title|tr|track|u|ul|var|video|wbr'.split('|');
for (let tag of htmlTags) {
window['$' + tag] = createElement.bind(null, tag);
}
Пример:
$a($b('GOOGLE'), { href: 'http://www.google.com/' }).outerHTML
"<a href="http://www.google.com/"><b>GOOGLE</b></a>"
// Можно в любом порядке передавать аргументы
$a({ href: 'http://www.google.com/' }, $b('GOOGLE')).outerHTML