const chainScripts = src =>
src.reduce((acc, n) => {
return acc.then(() => new Promise((resolve, reject) => {
const s = document.createElement('script');
s.onload = resolve;
s.onerror = reject;
s.src = n;
document.head.appendChild(s);
}));
}, Promise.resolve());
const inputs = new DOMParser()
.parseFromString(str, 'text/html')
.querySelectorAll('input');
// или
const { elements: inputs } = document
.createRange()
.createContextualFragment(str)
.querySelector('form');
// или
const inputs =
(el => (el.innerHTML = str, el.getElementsByTagName('input')))
(document.createElement('div'));const getName = el => el.name;
// или
const getName = el => el.getAttribute('name');
// или
const getName = el => el.attributes.name.value;const names = Array.from(inputs, getName);
// или
const names = Array.prototype.map.call(inputs, getName);
// или
const names = [];
for (const n of inputs) {
names.push(getName(n));
}
// или
const names = [];
for (let i = 0; i < inputs.length; i++) {
names[i] = getName(inputs[i]);
}
// или
const names = (function get(i, n = inputs.item(i)) {
return n ? [ getName(n), ...get(i + 1) ] : [];
})(0);
const nodeToObj = node => ({
type: node.nodeType,
value: node.nodeValue,
tag: node.tagName,
childNodes: Array.from(node.childNodes, nodeToObj),
attributes: node.attributes && Array.from(
node.attributes,
({ name, value }) => ({ name, value })
),
});
const nodeToJSON = (node, ...args) =>
JSON.stringify(nodeToObj(node), ...args);const json = nodeToJSON(document.querySelector('.menu'), null, 2);
document.body.insertAdjacentHTML('beforeend', `<pre>${json}</pre>`);
const class1 = 'item';
const class2 = 'in';
const key = 'price';
const attr = `data-${key}`;const getValue = el => +el.dataset[key];
// или
const getValue = el => parseFloat(el.getAttribute(attr));
// или
const getValue = el => Number(el.attributes[attr].value);const sum = Array.prototype.reduce.call(
document.querySelectorAll(`.${class1}.${class2}`),
(acc, n) => acc + getValue(n),
0
);
// или
let sum = 0;
for (const n of document.getElementsByClassName(class1)) {
sum += getValue(n) * n.classList.contains(class2);
}
const getNested = (root, ...keys) => keys
.flat(Infinity)
.flatMap(n => typeof n === 'string' ? n.split('.') : n)
.reduce((p, c) => p != null ? p[c] : void 0, root);const id = getNested(e, 'path.1.attributes.uid.textContent');
// или
const id = getNested(e, 'path', 1, 'attributes', 'uid', 'textContent');
// или
const id = getNested(e, 'path.1', [ 'attributes', [ 'uid' ] ], 'textContent');const id = e?.path?.[1]?.attributes?.uid?.textContent;
function handler(e) {
console.log('hello, world!!');
this.removeEventListener(e.type, handler);
}
document.addEventListener('click', handler);document.addEventListener('click', handler, { once: true });
const filterAndGroupAdjacent = (data, filterFn) =>
Array.prototype.reduce.call(
data,
(acc, n, i, a) => {
if (filterFn(n, i, a)) {
const len = acc[0].length;
(acc[1] === ~-i ? acc[0][~-len] : (acc[0][len] = [])).push(n);
acc[1] = i;
}
return acc;
},
[ [], null ]
)[0];// достаём нечётные числа
filterAndGroupAdjacent(
[ 1, 7, 3, 2, 3, 4, 4, 9, 5 ],
n => n & 1
) // [ [1,7,3], [3], [9,5] ]
// буквы в верхнем регистре
filterAndGroupAdjacent(
'1_Df+HNU*@qpJM!x',
RegExp.prototype.test.bind(/[A-Z]/)
) // [ ["D"], ["H","N","U"], ["J","M"] ]
phone.value = phone.value.replace(/[^+0-9]/g, '').slice(0, 11);
const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');
const TILE_SIDE = 32;
let pickX = 0;
let pickY = 0;
const ground = new Image();
ground.src = 'Ground.png';
const pick = new Image();
pick.src = 'Pick.png';
document.addEventListener('keydown', function(e) {
switch (e.key) {
case 'w': pickY -= TILE_SIDE; break;
case 'a': pickX -= TILE_SIDE; break;
case 's': pickY += TILE_SIDE; break;
case 'd': pickX += TILE_SIDE; break;
default: return;
}
draw();
});
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let x = 0; x < canvas.width; x += TILE_SIDE) {
for (let y = 0; y < canvas.height; y += TILE_SIDE) {
ctx.drawImage(ground, x, y);
}
}
ctx.drawImage(pick, pickX, pickY);
}
draw();
<div class="accordionFaq"></div>const playersOptions = [
{ source: '...' },
{ source: '...' },
...
];
$('.accordionFaq').html(playersOptions.map((n, i) => `
<div class="accordionFaq-item">
<div class="accordionFaq-head js-accordionFaq-head">
Video #${i}
</div>
<div class="accordionFaq-body">
<div id="player${i}"></div>
</div>
</div>
`).join('')).on('click', '.accordionFaq-head', function(e) {
const index = $(this).closest('.accordionFaq-item').index();
$('.accordionFaq-item', e.delegateTarget).each(function(i) {
const
$this = $(this),
isClicked = i === index,
active = isClicked && !$this.hasClass('active');
$(this)
.toggleClass('active', active)
.find('.accordionFaq-body')
[isClicked ? 'slideToggle' : 'slideUp']();
playersOptions[i].player[active ? 'play' : 'pause']();
});
});
playersOptions.forEach((n, i) => {
n.player = new Clappr.Player({
source: n.source,
parentId: `#player${i}`,
});
});
const getNum = () => new Promise(r => setTimeout(r, 1000, Math.random() * 100 | 0));
(async () => {
console.time('xxx');
const [ result1, result2 ] = [ await getNum(), await getNum() ];
console.log(result1, result2);
console.timeEnd('xxx');
})();
(async () => {
console.time('yyy');
const [ result1, result2 ] = await Promise.all([ getNum(), getNum() ]);
console.log(result1, result2);
console.timeEnd('yyy');
})();
$('table').on('change', 'select', ({ target: t }) => {
const isNone = t.value === 'none';
$(t)
.closest('td')
[isNone ? 'nextAll' : 'next']()
.find('select')
.prop('disabled', isNone)
.val((i, val) => isNone ? 'none' : val);
});document.querySelector('table').addEventListener('change', ({ target: t }) => {
if (t.tagName === 'SELECT') {
const isNone = t.value === 'none';
const { cellIndex: i, parentNode: { children } } = t.closest('td');
[...children].slice(i + 1, isNone ? undefined : i + 2).forEach(n => {
const select = n.querySelector('select');
select.disabled = isNone;
select.value = isNone ? 'none' : select.value;
});
}
});