document.addEventListener('click', ((val, e) => {
console.log(val);
}).bind(null, isOpenInputForSearch));
toggle не срабатывает при клике на элемент. Не присваивает классы и не убирает.
Клик происходит по label
const result = [...arr]
.sort((a, b) => a.length - b.length)
.reduce((acc, n) => (
acc.some(m => n.includes(m)) || acc.push(n),
acc
), []);
const result = arr.filter((n, i, a) => !a.some((m, j) => i !== j && n.includes(m)));
const className = 'doc';
.const wrapFirstWord = el =>
el.innerHTML = el.innerText.replace(/\S+/, '<span>$&</span>');
// или
const wrapFirstWord = el =>
el.innerHTML = el.innerHTML
.split(' ')
.map((n, i) => i ? n : `<span>${n}</span>`)
.join(' ');
// или
function wrapFirstWord(el) {
const i = el.textContent.indexOf(' ');
const span = document.createElement('span');
span.append(el.textContent.slice(0, i));
el.replaceChildren(span, el.textContent.slice(i));
}
// или
function wrapFirstWord({ childNodes: [ text ] }) {
const [ , first, rest ] = text.nodeValue.match(/(\S+)(.*)/);
const span = document.createElement('span');
span.appendChild(new Text(first));
text.nodeValue = rest;
text.parentNode.insertBefore(span, text);
}
document.querySelectorAll(`.${className}`).forEach(wrapFirstWord);
// или
for (const n of document.getElementsByClassName(className)) {
wrapFirstWord(n);
}
if(num=>5&&num<=10){
=>
- никакой это не оператор сравнения.true
. const pick = (obj, keys) => Object.fromEntries(keys.map(k => [ k, obj[k] ]));
const newArr = arr.map(n => pick(n, keys));
const pick = (obj, keys) =>
Object.fromEntries(Object.entries(obj).filter(m => keys.includes(m[0])));
// или
const pick = (obj, keys) =>
keys.reduce((acc, n) => (obj.hasOwnProperty(n) && (acc[n] = obj[n]), acc), {});
a
, показывать пытаетесь img
.document.querySelectorAll('.photos img').forEach(n => {
n.parentNode.style.display = +n.alt === alt ? '' : 'none';
});
function getTimes(start, end, interval) {
const [ s, e ] = [ start, end ].map(n => moment(n, 'HH:mm'));
const result = [];
if (s > e) {
e.add(1, 'day');
}
for (; s <= e; s.add(interval, 'minutes')) {
result.push(s.format('HH:mm'));
}
return result;
}
function getTimes(start, end, interval) {
const [ s, e ] = [ start, end ].map(n => new Date(`2000-01-01 ${n}`));
const result = [];
if (s > e) {
e.setDate(e.getDate() + 1);
}
for (; s <= e; s.setMinutes(s.getMinutes() + interval)) {
result.push(s.toTimeString().split(':', 2).join(':'));
// или
result.push(s.toLocaleTimeString('ru', {
hour: '2-digit',
minute: '2-digit',
}));
}
return result;
}
const times = getTimes('10:00', '18:00', 30);
. const valueAndClass = [
[ 'yes', 'bg-success' ],
[ 'no', 'bg-warning' ],
];
document.querySelector('table').addEventListener('change', e => {
for (const td of e.target.closest('tr').cells) {
for (const [ value, className ] of valueAndClass) {
td.classList.toggle(className, value === e.target.value);
}
}
});
bg-primary
у ячеек, добавьте его строкам, а обработчик события change пусть будет таким, например:document.querySelector('table').addEventListener('change', ({ target: t }) => {
const tr = t.closest('tr');
valueAndClass.forEach(n => tr.classList.toggle(n[1], n[0] === t.value));
});
const $container = $('.promo__cats');
$container.append(...$container
.children()
.get()
.map(n => [ n, +$('.promo__price', n).text().replace(/\D/g, '') ])
.sort((a, b) => a[1] - b[1])
.map(n => n[0])
);
cells.push(xCells); buffCells.push(xCells);
cells = buffCells;
const container = document.querySelector('селектор контейнера с select\'ами');
const selectSelector = 'селектор select\'ов';
const input = document.querySelector('селектор input\'а');
const updateInput = selects => input.value = Array.from(selects, n => n.value).join(' ');
container.addEventListener('change', function() {
updateInput(this.querySelectorAll(selectSelector));
});
// или
const selects = container.querySelectorAll(selectSelector);
const onChange = updateInput.bind(null, selects);
selects.forEach(n => n.addEventListener('change', onChange));
function parallel(tasks, onAllTasksComplete) {
const results = [];
let numCompleted = 0;
function onTaskComplete(index, result) {
results[index] = result;
if (++numCompleted === tasks.length) {
onAllTasksComplete(results);
}
}
for (let i = 0; i < tasks.length; i++) {
const onComplete = r => onTaskComplete(i, r);
const result = tasks[i](onComplete);
if (result !== undefined) {
onComplete(result);
}
}
}
const process = (funcs, initialArg) => funcs.reduce((arg, f) => f(arg), initialArg);
const getMonthNameInGenitiveCase = (date = new Date) =>
date.toLocaleString('ru', {
month: 'long',
day: 'numeric',
}).split(' ')[1];
const getMonthNameInGenitiveCase = (date = new Date) =>
[
'января', 'февраля', 'марта', 'апреля', 'мая', 'июня',
'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря',
][date.getMonth()];
const openSelector = '[data-target]';
const closeSelector = '.modal__close';
const modalSelector = '.modal';
const activeClass = 'modal--active';
document.addEventListener('click', ({ target: t }) => {
const open = t.closest(openSelector);
if (open) {
document.querySelector(`#${open.dataset.target}`).classList.add(activeClass);
} else {
t.closest(closeSelector)?.closest(modalSelector).classList.remove(activeClass);
}
});
const onClick = (selector, handler) => document
.querySelectorAll(selector)
.forEach(n => n.addEventListener('click', handler));
onClick(openSelector, ({ currentTarget: { dataset: { target } } }) => {
document.querySelector(`#${target}`).classList.add(activeClass);
});
onClick(closeSelector, e => {
e.currentTarget.closest(modalSelector).classList.remove(activeClass);
});
const obj = {
val: 1,
valueOf() {
return this.val ^= 1;
},
};
// или
const obj = {
val: '1',
toString() {
return this.val = '1'.slice(this.val.length);
},
};
// или
const obj = {
val: true,
[Symbol.toPrimitive]() {
return this.val = !this.val;
},
};
console.log(obj == false, obj == true); // true true
console.log(...Array.from({ length: 5 }, () => +obj)); // 0 1 0 1 0
function mustStay(n) {
for (const m of arr2) {
if (m.content.insuranceType === n.value) {
return false;
}
}
return true;
}
// или
const mustStay = n => arr2.every(m => m.content.insuranceType !== n.value);
// или
const mustStay = function(n) {
return !this.has(n.value);
}.bind(new Set(arr2.map(n => n.content.insuranceType)));
// или
const mustStay = n =>
(function next(i) {
return i >= arr2.length
? true
: arr2[i].content.insuranceType !== n.value && next(-~i);
})(0);
for (let i = 0; i < arr1.length; i++) {
if (!mustStay(arr1[i])) {
for (let j = i--; ++j < arr1.length; arr1[j - 1] = arr1[j]) ;
arr1.pop();
}
}
// или
arr1.reduceRight((_, n, i, a) => mustStay(n) || a.splice(i, 1), null);
// или
arr1.splice(0, arr1.length, ...arr1.filter(mustStay));
// или
arr1.length -= arr1.reduce((acc, n, i, a) => (
a[i - acc] = n,
acc + !mustStay(n)
), 0);
const steps = [ /* ... */ ];
let iStep = 0;
const question = document.querySelector('.quiz__question');
const answers = document.querySelector('.quiz__answers');
const prev = document.querySelector('.quiz__button_prev');
const next = document.querySelector('.quiz__button_next');
prev.addEventListener('click', () => nextStep(-1));
next.addEventListener('click', () => nextStep(+1));
function nextStep(stepChange) {
iStep = Math.max(0, Math.min(steps.length - 1, iStep + stepChange));
prev.disabled = iStep === 0;
next.disabled = iStep === steps.length - 1;
question.innerHTML = steps[iStep].question;
answers.innerHTML = steps[iStep].answers.map(n => `<li>${n}</li>`).join('');
}
nextStep(0);