document.addEventListener('click', ({ target: t }) => {
if (t.classList.contains('xxx')) {
currColor.style.backgroundColor = t.nextElementSibling.textContent;
}
// или
if (t.matches('.xxx')) {
currColor.style.backgroundColor = getComputedStyle(t).backgroundColor;
}
});
const findMin = obj =>
(obj.children || []).reduce((min, n) => (
n = findMin(n),
min.value < n.value ? min : n
), obj);
const count = obj =>
(obj.children || []).reduce((acc, n) => {
const c = count(n);
acc.num += c.num;
acc.sum += c.sum;
return acc;
}, { num: 1, sum: obj.value });
const c = count(obj);
const average = c.sum / c.num;
const tower = length =>
Array.from({ length }, (n, i) => Array(2)
.fill(' '.repeat(length - i - 1))
.join('*'.repeat(i * 2 + 1))
);
const tower = length =>
Array.from({ length }, (n, i) => (
n = Array(length - i).join(' '),
n + Array(-~i << 1).join('*') + n
));
const FILTER_VALUE = 'eg';
const filteredArr = arr.reduce((acc, el) => {
const items = el.items
.filter(n => n.keywords.some(m => m.includes(FILTER_VALUE)))
.map(n => ({ ...n, keywords: [...n.keywords] }));
if (items.length) {
acc.push({ ...el, items });
}
return acc;
}, []);
const $initial = $('.some-div').clone();
$('.some-div').replaceWith($initial);
$('.some-div').replaceWith($initial.clone());
function getTableData(table) {
if (typeof table === 'string') {
table = document.querySelector(table);
}
return Array.from(table.querySelectorAll('tbody tr'), tr => {
return Object.fromEntries(Array.from(tr.cells, td => [
td.dataset.name,
td.querySelector('input').value,
]));
});
}
const data1 = getTableData('#table1');
const data2 = getTableData(document.querySelector('#table2'));
document.querySelector('textarea').addEventListener('keydown', e => e.preventDefault());
<textarea readonly></textarea>
const text = '|||';
.$el.children().slice(1).before(text);
// или
$el.children(':nth-child(n + 2)').before(text);
// или
$el.find('> :nth-last-child(n + 2)').after(text);
Array.prototype.forEach.call(
el.children,
(n, i) => i && el.insertBefore(document.createTextNode(text), n)
);
// или
for (const n of el.children) {
if (n.nextElementSibling) {
n.insertAdjacentText('afterend', text);
}
}
// или
for (let i = 1; i < el.children.length; i++) {
el.children[i].before(new Text(text));
}
const gallerySelector = '.js-product__item';
const previewSelector = '.view__item img';
const mainImageSelector = '.js-product__img--current';
const showImage = preview => preview
.closest(gallerySelector)
.querySelector(mainImageSelector)
.src = preview.src;
document.addEventListener('click', ({ target: t }) => {
if (t.matches(previewSelector)) {
showImage(t);
}
});
// или
document.querySelectorAll(previewSelector).forEach(function(n) {
n.addEventListener('click', this);
}, e => showImage(e.target));
const keys = [
[
{ on: [ 'ё', 'Ё' ], off: [ '`', '~' ], name: 'Backquote' },
{ on: [ '1', '!' ], off: [ '1', '!' ], name: 'Digit1' },
...
],
...
];
document.querySelector('.keyboard').innerHTML = keys.map(row => `
<div class="row">${row.map(n => `
<div class="key">
<span class="${n.name} on">
<span class="case down">${n.on[0]}</span>
<span class="case up">${n.on[1]}</span>
</span>
<span class="${n.name} off">
<span class="case down">${n.off[0]}</span>
<span class="case up">${n.off[1]}</span>
</span>
</div>`).join('')}
</div>`).join('');
const urls = [
'http://sitename.net/somedirectory/14545/',
'http://sitename.net/somedirectory/14545/count-1145',
'http://sitename.net/somedirectory/14545/specific-345',
'http://sitename.net/somedirectory/14545/count-1145/specific-345',
];
const getParams = (url, params) =>
params instanceof Array && params.length
? (url.match(RegExp(`(${params.join('|')})-\\d+`, 'g')) || [])
.map(n => n.split('-'))
.reduce((acc, n) => (acc[n[0]] = n[1], acc), {})
: {};
const params = urls.map(n => getParams(n, [ 'count', 'specific' ]));
const getParams = url =>
Object.fromEntries((url
.match(/[a-z]+-\d+/g) || [])
.map(n => n.split('-'))
);
const [ first, second ] = [...arr]
.sort((a, b) => b.id - a.id)
.slice(0, 2)
.map(n => n.name);
const [ { name: first }, { name: second } ] = arr.reduce((acc, n) => {
if (!(acc[0].id >= n.id)) {
acc[1] = acc[0];
acc[0] = n;
} else if (!(acc[1].id >= n.id)) {
acc[1] = n;
}
return acc;
}, [ {}, {} ]);
cildren
const copyTree = (tree, f) =>
tree.map(n => {
n = f instanceof Function ? f(n) : { ...n };
if (n.children instanceof Array) {
n.children = copyTree(n.children, f);
}
return n;
});
const dataCopy = copyTree(data, ({ name: key, ...x }) => ({ key, ...x }));
[...Array(n)]
. Но, учитывая реально решаемую задачу, не надо никаких массивов, состоящих из undefined, заполняйте сразу тем, чем надо:const sequence = (length, pattern) =>
pattern instanceof Function
? Array.from({ length }, pattern)
: Array(length).fill(pattern);
const select = document.querySelector('#country');
const value = 'europe';
const options = select.querySelectorAll(`option[value*="${value}"]`);
const options = Array.prototype.filter.call(
select.options,
n => n.value.includes(value)
);
const options = [];
for (const n of select.children) {
if (n.value.indexOf(value) !== -1) {
options.push(n);
}
}
document.querySelector('.allstatus-btn').addEventListener('click', () => {
const items = Object.fromEntries(Array.from(
document.querySelectorAll('.number-all'),
n => [ n.innerText, n ]
));
fetch('https://api.novaposhta.ua/v2.0/json/', {
method: 'POST',
body: JSON.stringify({
modelName: 'TrackingDocument',
calledMethod: 'getStatusDocuments',
methodProperties: {
Documents: Object.keys(items).map(n => ({
DocumentNumber: n,
Phone: '',
})),
},
apiKey: '',
}),
})
.then(r => r.json())
.then(r => r.data.forEach(n => items[n.Number].innerHTML += n.Status));
});