menu.addEventListener('click', ({ target: t }) => {
if (t.tagName === 'SPAN') {
const parent = t.parentNode;
parent.classList.toggle('active');
for (const n of menu.querySelectorAll('.active')) {
if (n !== parent) {
n.classList.toggle('active', n.contains(parent));
}
}
}
});
- .menu_list_item.active .submenu {
+ .active > .submenu {
- .submenu_list_item.active .product {
+ .active > .product {
const container = document.querySelector('#menu');
const itemSelector = 'li';
const buttonSelector = `${itemSelector} span`;
const activeClass = 'active';
container.addEventListener('click', function(e) {
const item = e.target.closest(buttonSelector)?.closest(itemSelector);
if (item) {
item.classList.toggle(activeClass);
this.querySelectorAll(`.${activeClass}`).forEach(n => {
if (n !== item) {
n.classList.toggle(activeClass, n.contains(item));
}
});
}
});
const items = document.querySelectorAll('.faq__input');
const onChange = ({ target: t }) => t
.closest('.faq__items')
.querySelectorAll('.faq__question--top')
.forEach(n => n.classList.toggle('active', n.nextElementSibling.checked));
items.forEach(n => n.addEventListener('change', onChange));
.faq__item
вместо .faq__question--top
. Если в будущем задумаете стилизовать внутри выбранного .faq__item
элементы, находящиеся за пределами .faq__question--top
, то не придётся переписывать js-код.const itemSelector = '.faq__item';
const radioSelector = '.faq__input';
const activeClass = 'active';
const toggleActiveClass = radioGroupName => document
.querySelectorAll(`${radioSelector}[name="${radioGroupName}"]`)
.forEach(n => n.closest(itemSelector).classList.toggle(activeClass, n.checked));
document.querySelectorAll(radioSelector).forEach(function(n) {
n.addEventListener('change', this);
}, e => toggleActiveClass(e.target.name));
document.addEventListener('change', ({ target: t }) => {
if (t.matches(radioSelector)) {
toggleActiveClass(t.name);
}
});
const result = array2.filter(function(n) {
return this.has(n.code);
}, new Set(array1.map(n => n.value)));
const obj2 = Object.fromEntries(array2.map(n => [ n.code, n ]));
const result = array1.reduce((acc, n) => ((n = obj2[n.value]) && acc.push(n), acc), []);
const result = array2.filter(n => array1.some(m => m.value === n.code));
e.target.dataset.followerStyle
e.target
? Ну, когда вы наводите курсор на слайд с data-атрибутом. На тот слайд, который не видно за вложенной в него картинкой.target
хватать, а пытаться найти у него предка с нужным вам атрибутом. // значения withSeat вместо раскладывания в отдельные переменные собираете в объект
const withSeat = {
adult: 1,
teenager: 1,
babe: 0,
};
const passengers = cabins.flatMap(n => Object
.entries(n)
.flatMap(([ k, v ]) => Array.from(
{ length: v },
() => ({ withSeat: withSeat[k] })
))
);
const obj = Object.fromEntries(Object
.entries(arr
.flatMap(Object.entries)
.reduce((acc, n) => ((acc[n[0]] ??= new Set).add(n[1]), acc), {}))
.map(([ k, v ]) => [ k, v.size === 1 ? [...v][0] : null ])
);
const obj = arr.reduce((acc, n) => (
Object.keys(n).forEach(k => {
acc[k] = Object.hasOwn(acc, k) && n[k] !== acc[k] ? null : n[k];
}),
acc
), {});
formatDate(date) {
const today = new Date();
return [ 'getFullYear', 'getMonth', 'getDate' ].every(n => date[n]() === today[n]())
? 'Today'
: flatpickr.formatDate(date, 'j M');
},
const groupSelector = 'fieldset.js-tree-box';
const mainSelector = 'legend input';
const itemSelector = 'legend + span input';
const activeClass = 'active';
document.addEventListener('change', ({ target: t }) => {
const group = t.closest(groupSelector);
if (group) {
const main = group.querySelector(mainSelector);
const items = [...group.querySelectorAll(itemSelector)];
if (main === t) {
items.forEach(n => n.checked = t.checked);
} else {
const numChecked = items.reduce((acc, n) => acc + n.checked, 0);
main.checked = numChecked === items.length;
main.indeterminate = 0 < numChecked && numChecked < items.length;
}
group.classList.toggle(activeClass, main.checked);
}
});
const sorted = (data, key) => Array
.from(data, n => [ n, key(n) ])
.sort((a, b) => a[1] - b[1])
.map(n => n[0]);
document.querySelector('.result').append(...sorted(
document.querySelector('.data').cloneNode(true).children,
n => +n.innerText
));
делегирование не работает
в консоли выдает "e.target.closest is not a function"
const hoverCellNum = hoverCell.getAttribute('data-tdnum');
document.addEventListener('mouseenter', ({ target: t }) => {
if (t.matches?.('td._hight-light__cell')) {
t.closest('tbody').querySelectorAll('.table-big__row').forEach(n => {
n.cells[t.cellIndex].classList.add('_hover');
});
}
}, true);
document.addEventListener('mouseleave', e => {
if (e.target.matches?.('td._hight-light__cell')) {
document.querySelectorAll('._hover').forEach(n => n.classList.remove('_hover'));
}
}, true);
document.addEventListener('click', updateCounter);
document.addEventListener('input', updateCounter);
document.querySelectorAll('.tariff__counter').forEach(n => {
const max = n.dataset.seats;
n.querySelectorAll('.tariff__counter-max').forEach(m => m.innerText = max);
n.querySelectorAll('.amount').forEach(m => m.max = max);
n.querySelectorAll('button').forEach(m => m.dataset.change = m.innerText === '+' ? 1 : -1);
});
function updateCounter({ target: t }) {
const input = t.closest('.tariff__counter-block')?.querySelector('.amount');
if (input) {
const { min, max, value } = input;
input.value = Math.max(min, Math.min(max, (value | 0) + (t.dataset.change | 0)));
}
}
const keys = [ 'id', 'secondId' ];
const result = firstArray.map(n => secondArray.find(m => keys.every(k => n[k] === m[k])) ?? n);
const arrToTree = (arr, keys) =>
arr.reduce((acc, n) => (
keys.reduce((p, c, i) => p[n[c]] ??= i + 1 === keys.length ? n : {}, acc),
acc
), {});
const keys = [ 'id', 'secondId' ];
const tree = arrToTree(secondArray, keys);
const result = firstArray.map(n => keys.reduce((p, c) => p?.[n[c]], tree) ?? n);
const arrToTree = (arr, keys) =>
arr.reduce((acc, n) => (
keys(n).reduce(
(p, c, i, a) => p.set(c, p.get(c) ?? (-~i === a.length ? n : new Map)).get(c),
acc
),
acc
), new Map);
const keys = n => [ n.id, n.secondId ];
const result = firstArray.map(function(n) {
return keys(n).reduce((p, c) => p?.get(c), this) ?? n;
}, arrToTree(secondArray, keys));
function getLeaves(tree) {
const result = [];
for (const stack = [...tree]; stack.length;) {
const n = stack.pop();
if (Array.isArray(n.children) && n.children.length) {
stack.push(...n.children);
} else {
result.push(n);
}
}
return result.reverse();
}
function getLeaves(tree) {
const result = [];
const stack = [];
for (let arr = tree, i = 0; i < arr.length || stack.length; i++) {
if (i === arr.length) {
[ i, arr ] = stack.pop();
} else if (arr[i].children instanceof Array && arr[i].children.length) {
stack.push([ i, arr ]);
[ i, arr ] = [ -1, arr[i].children ];
} else {
result.push(arr[i]);
}
}
return result;
}
function getLeaves([...tree]) {
for (let i = 0; i < tree.length; i++) {
const c = tree[i].children;
if (c?.constructor === Array && c.length) {
tree.splice(i--, 1, ...c);
}
}
return tree;
}
const groupSum = (arr, idKey, ...sumKeys) =>
Object.values(arr.reduce((acc, n) => (
acc[n[idKey]] ??= sumKeys.reduce((group, k) => (group[k] = 0, group), {...n}),
sumKeys.forEach(k => acc[n[idKey]][k] += n[k]),
acc
), {}));
const result = groupSum(arr, 'product', 'price', 'selling_price', 'quantity');