const queryIfSelector = f => x =>
f(typeof x === 'string' ? document.querySelector(x) : x);const getTableData = queryIfSelector(table =>
Array.from(table.querySelectorAll('tbody tr'), tr =>
Object.fromEntries(Array.from(tr.querySelectorAll('td'), td => [
td.getAttribute('data-name'),
td.querySelector('input').value,
]))
)
);
// или
const getTableData = queryIfSelector(table =>
Array.prototype.flatMap.call(table.tBodies, tbody =>
Array.prototype.map.call(tbody.rows, tr =>
Array.prototype.reduce.call(tr.cells, (acc, td) => (
acc[td.dataset.name] = td.firstElementChild.value,
acc
), {})
)
)
);
// или
const getTableData = queryIfSelector(table => {
const result = [];
const numHeadRows = table.querySelectorAll('thead tr').length;
for (const input of table.querySelectorAll('tbody input')) {
const td = input.closest('td');
const i = td.parentNode.rowIndex - numHeadRows;
const item = result[i] = result[i] || {};
item[td.attributes['data-name'].value] = input.value;
}
return result;
});const data1 = getTableData('#table1');
const data2 = getTableData(document.querySelector('#table2'));
document.querySelector('textarea').addEventListener('keydown', e => e.preventDefault());<textarea readonly></textarea>
const el = document.querySelector('здесь селектор родительского элемента');
const text = '|||';Array.prototype.forEach.call(
el.children,
(n, i) => i && n.before(text)
);
// или
for (const n of el.children) {
if (n.nextElementSibling) {
n.insertAdjacentText('afterend', text);
}
}
// или
for (let i = 1; i < el.children.length; i++) {
el.insertBefore(document.createTextNode(text), el.children[i]);
}
// или
(function insert(i, n = el.children.item(i)) {
if (n) {
n.replaceWith(text, n);
insert(-~i);
}
})(1);
// или
el.querySelectorAll(':scope > * + *').forEach(n => {
n.outerHTML = text + n.outerHTML;
});
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 }) =>
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;
}, [ {}, {} ]);
cildrenconst 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));
});
function createTree(data) {
const obl = {};
const org = {};
const podr = {};
data.forEach(n => {
obl[n.obl.id] = { ...n.obl, children: [] };
org[n.org.id] = { ...n.org, children: [] };
podr[n.podr.id] = { ...n.podr, children: [] };
});
data.forEach(n => podr[n.podr.id].children.push({ ...n.dolzh }));
Object.values(org).forEach(n => obl[n.parent_obl].children.push(n));
Object.values(podr).forEach(n => org[n.parent_org].children.push(n));
return Object.values(obl);
}
const tree = createTree(arr);
Array.from([...str].reduce((acc, n) => acc.set(n, -~acc.get(n)), new Map), n => n[1] + n[0])str.split('').sort().join('').match(/(.)\1*/g).map(n => n.length + n[0])Array.from(new Set(str), n => str.replace(RegExp(`[^${n}]`, 'g'), '').length + n)
const getLastDeepestElement = function(el) {
return this(el, 0)[0];
}.bind(function get(el, level) {
return [...el.children].reduce((p, c) => (
c = get(c, -~level),
p[1] > c[1] ? p : c
), [ el, level ]);
});function getLastDeepestElement(el) {
let result = [ el, 0 ];
for (const stack = [ result ]; stack.length;) {
const n = stack.pop();
result = n[1] > result[1] ? n : result;
stack.push(...Array.from(n[0].children, m => [ m, n[1] + 1 ]));
}
return result[0];
}const getDeepestLastElement = el =>
el.lastElementChild
? getDeepestLastElement(el.lastElementChild)
: el;const getDeepestLastElement = el => Array
.from(el.querySelectorAll('*'))
.pop() || el;
// или
function getDeepestLastElement(el) {
for (let c; (c = el.children).length; el = c[~-c.length]) ;
return el;
}
.on('click', function(e) {
e.stopPropagation();
const valuesShow = [ 2000, ещё какое-то значение, и ещё, и ещё, ... ];$('#sample_form_deliv').change(function({ target: { value } }) {
$('#sample_form_pay .input-label:eq(2)').toggle(valuesShow.includes(+value));
});
Array.prototype.reduce.call(
document.querySelector('table').rows,
(acc, n) => {
if (!n.classList.contains('no')) {
acc[acc.length - 1].info.push({
subtitle: n.cells[0].textContent,
cell: n.cells[1].textContent,
});
} else if (!n.querySelector('.no2')) {
acc.push({
title: n.querySelector('.car').textContent,
info: [],
});
}
return acc;
},
[]
)
$(this).parents('.portfolio')function parents(el, selector) {
const p = [];
while ((el = el.parentNode) !== document && el) {
(!selector || el.matches(selector)) && p.push(el);
}
return p;
}
parents(this, '.portfolio')$(this).parent('.portfolio')this.parentNode.classList.contains('portfolio') ? this.parentNode : null$(this).children('.portfolio')[...this.children].filter(n => n.classList.contains('portfolio'))
// или
Array.prototype.filter.call(this.children, n => n.matches('.portfolio'))
// или
this.querySelectorAll(':scope > .portfolio')$(this).find('.portfolio')this.querySelectorAll('.portfolio')$(this).next('.portfolio')(el => el && el.matches('.portfolio') ? el : null)(this.nextElementSibling)