вторая не работает
.grade-item
обрабатывать, а только те, у кого в предках тот же .grade-item-block
, что и у кликнутого.const container = document.querySelector('.nav-student-new-lesson');
const blockSelector = '.grade-item-block';
const itemSelector = `${blockSelector} .grade-item`;
const colors = {
grades: [
[ 5, 'rgba(150, 255, 0, 0.3)' ],
[ 3, 'rgba(255, 150, 0, 0.3)' ],
[ 1, 'rgba(255, 0, 0, 0.3)' ],
],
default: 'white',
};
function updateGrade(item) {
const items = item.closest(blockSelector).querySelectorAll(itemSelector);
const grade = 1 + Array.prototype.indexOf.call(items, item);
const color = colors.grades.find(n => n[0] <= grade)[1];
items.forEach((n, i) => n.style.background = i < grade ? color : colors.default);
}
container.addEventListener('click', e => {
const item = e.target.closest(itemSelector);
if (item) {
updateGrade(item);
}
});
.grade-item
:container.querySelectorAll(itemSelector).forEach(function(n) {
n.addEventListener('click', this);
}, e => updateGrade(e.currentTarget));
const container = document.querySelector('#list');
const activeClass = 'active';
container.firstElementChild.classList.add(activeClass);
document.addEventListener('keydown', e => {
const nextElKey = ({
ArrowDown: 0,
ArrowUp: 1,
})[e.key];
const currEl = container.querySelector(`:scope > .${activeClass}`);
const nextEl =
currEl[[ 'nextElementSibling', 'previousElementSibling' ][nextElKey]]/* ??
container[[ 'firstElementChild', 'lastElementChild' ][nextElKey]]*/;
// если надо, чтобы при переходе от последнего к следующему элементу
// активным становился первый, а при переходе от первого к предыдущему
// активным становился последний, достаточно удалить многострочное
// комментирование выше
if (nextEl) {
currEl.classList.remove(activeClass);
nextEl.classList.add(activeClass);
}
});
const next = function(step) {
this[1][this[0]].classList.remove(activeClass);
this[0] = Math.max(0, Math.min(this[1].length - 1, this[0] + step));
// или, если надо, чтобы выделение по кругу бегало
// this[0] = (this[0] + step + this[1].length) % this[1].length;
this[1][this[0]].classList.add(activeClass);
}.bind([ 0, container.children ]);
next(0);
document.addEventListener('keydown', ({ key }) => {
const step = +(key === 'ArrowDown') || -(key === 'ArrowUp');
if (step) {
next(step);
}
});
Object.values(Object.fromEntries(arr.map(n => [ n.user.id, n ])))
// или, если в результирующий массив должны попадать те из "одинаковых" элементов,
// что расположены в исходном массиве первыми
Object.values(arr.reduce((acc, n) => (acc[n.user.id] ??= n, acc), {}))
// или, если также надо сохранять взаимное расположение элементов
arr.filter(function({ user: { id: n } }) {
return !(this[n] = this.hasOwnProperty(n));
}, {})
function* unique(data, key = n => n) {
const getKey = key instanceof Function ? key : n => n[key];
const keys = new Set;
for (const n of data) {
const k = getKey(n);
if (!keys.has(k)) {
keys.add(k);
yield n;
}
}
}
const result = [...unique(arr, n => n.user.id)];
.Array.from(unique([{id: 1}, {id: 2}, {id: 1}, {id: 1} ], 'id')) // [{id: 1}, {id: 2}]
''.concat(...unique('ABBA')) // 'AB'
.for (const n of unique(Array(20).keys(), n => Math.sqrt(n) | 0)) {
console.log(n); // 0 1 4 9 16
}
const radios = document.querySelectorAll('[name="radios"]');
const selects = Array.from(radios, n => n.nextElementSibling);
const onChange = e => selects.forEach(n => n.disabled = n !== e.target.nextElementSibling);
radios.forEach(n => n.addEventListener('change', onChange));
const arithmeticProgression = ({ length, a1 = 0, d = 1 }) =>
Array.from(
{ length },
(n, i) => a1 + i * d
);
const arr = arithmeticProgression({
length: 10,
a1: 6,
d: 3,
});
function* arithmeticProgression(a1, d, length) {
for (let i = 0; i < length; i++) {
yield a1 + i * d;
}
}
for (const n of arithmeticProgression(100, 10, 5)) {
console.log(n);
}
console.log(Array.from(arithmeticProgression(10, -7, 10)));
const voidTags = [ 'input', 'img', 'br', 'hr', ещё какой-то тэг, и ещё, ... ];
function createHTML(data) {
const attrs = Object
.entries(data.attrs ?? {})
.map(n => `${n[0]}="${n[1]}"`)
.join(' ');
const startTag = `<${data.tagName}${attrs && (' ' + attrs)}>`;
if (voidTags.includes(data.tagName)) {
return startTag;
}
const children = (data.subTags ?? [])
.map(createHTML)
.join('');
return `${startTag}${data.text ?? ''}${children}</${data.tagName}>`;
}
const search = ` ${str}.`;
const item = arr.find(n => n.includes(search));
const test = RegExp.prototype.test.bind(RegExp(`\\b${str}\\b`));
const items = arr.filter(test);
arr.map((n, i, a) => a.slice(0, i + 1).join(''))
// или
arr.reduce((acc, n) => (acc.push((acc.at(-1) ?? '') + n), acc), [])
(function xxx(arr, str = '') {
if (str.length === arr.length) {
return [];
}
const newStr = str.concat(arr[str.length]);
return [ newStr, ...xxx(arr, newStr) ];
})(arr)
overlay.click(e => {
if (e.target === e.delegateTarget) {
overlay.fadeOut();
}
});
// или
overlay.click(function(e) {
$(this).filter(e.target).fadeOut();
});
overlay
.click(() => overlay.fadeOut())
.children()
.click(e => e.stopPropagation());
$.each($.parseJSON(response), (k, v) => $(`.${k}`).text(v));
for (const [ k, v ] of Object.entries(JSON.parse(response))) {
document.querySelector(`.${k}`).innerText = v;
}
document.querySelector('.listing').after(...arrayWords.map(n => {
const p = document.createElement('p');
p.innerHTML = n;
return p;
}));
// или
document.querySelector('.listing').insertAdjacentHTML(
'afterend',
arrayWords.map(n => `<p>${n}</p>`).join('')
);
arrayWords.reduce((prev, n) => (
prev.after(document.createElement('p')),
prev.nextSibling.innerHTML = n,
prev.nextSibling
), document.querySelector('.listing'));
$('table').on('change', 'select', ({ target: t }) => {
$(t).replaceWith(t.value);
// или
$(t).parent().text(t.value);
});
document.querySelector('table').addEventListener('change', ({ target: t }) => {
if (t.tagName === 'SELECT') {
t.replaceWith(t.value);
}
// или
if (t instanceof HTMLSelectElement) {
t.parentNode.textContent = t.value;
}
// или
if (t.nodeName === 'SELECT') {
t.parentNode.replaceChild(new Text(t.value), t);
}
// или
t.matches('select') && (t.outerHTML = t.value);
});
progress.css('background-color', [
{ min: 100, color: '#47C965' },
{ min: 40, color: '#f5dd30' },
{ min: 0, color: '#bf4542' },
].find(n => n.min <= strength).color);
const tests = [ здесь перечисляете регулярные выражения ].map((n, i) => ({
regex: n,
message: error_wrap.attr(`data-error_${i + 1}`),
}));
const newArr = Object
.values(arr.reduce((acc, n, i) => ((acc[n] ??= []).push(i), acc), {}))
.reduce((acc, n) => (n.forEach(i => acc[i] = n.length > 1), acc), []);
// или
const newArr = arr.map(function(n) {
return this[n];
}, arr.reduce((acc, n) => (acc[n] = acc.hasOwnProperty(n), acc), {}));
// или
const count = arr.reduce((acc, n) => (acc[n] = (acc[n] ?? 0) + 1, acc), {});
const newArr = arr.map(n => count[n] > 1);
// или
const newArr = arr.map((n, i, a) => a.indexOf(n) !== a.lastIndexOf(n));
arr.forEach(function(n, i, a) {
a[i] = this.get(n) > 1;
}, arr.reduce((acc, n) => acc.set(n, -~acc.get(n)), new Map));
// или
const duplicates = arr.reduce((acc, n) => acc.set(n, acc.has(n)), new Map);
arr.splice(0, arr.length, ...arr.map(n => duplicates.get(n)));
$('select').change(function() {
const text = $(':checked', this).text();
console.log(text);
});
document.querySelector('select').addEventListener('change', function(e) {
const select = this;
// или
// const select = e.target;
// const select = e.currentTarget;
const [ option ] = select.selectedOptions;
// или
// const option = select[select.selectedIndex];
// const option = select.querySelector(':checked');
// const option = [...select.options].find(n => n.selected);
const text = option.text;
// или
// const text = option.textContent;
// const text = option.innerText;
console.log(text);
});
document.querySelector('#filter-input').addEventListener('input', e => {
const val = e.target.value.toLowerCase();
container.querySelectorAll('.title').forEach(n => {
n.closest('.card').style.display = n.innerText.includes(val)
? 'block'
: 'none';
});
});
const obj = Object.fromEntries(arr.map((n, i) => [ `answer${i + 1}`, n ]));
const obj = arr.reduce((acc, n, i) => (acc['answer' + ++i] = n, acc), {});
const obj = {};
for (const [ i, n ] of arr.entries()) {
obj['answer'.concat(-~i)] = n;
}
str[0] === str[0].toUpperCase()
/^[A-Z]/.test(str)
(c => 64 < c && c < 91)(str.charCodeAt(0))
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.includes(str.at(0))
$('.filter').change(({ target: t }) => {
$(`[name="${$(t).closest('.button').data('size')}"]`)
.closest('.product-box')
.toggleClass('hidden', !t.checked);
}).find(':checked').change();
const filter = document.querySelector('.filter');
filter.addEventListener('change', ({ target: t }) => {
const size = t.closest('.button').dataset.size;
document.querySelectorAll(`[name="${size}"]`).forEach(n => {
n.closest('.product-box').classList.toggle('hidden', !t.checked);
});
});
filter.querySelectorAll(':checked').forEach(n => {
n.dispatchEvent(new Event('change', { bubbles: true }));
});
<div>
<input id="password">
</div>
<div>
<div>Сложность пароля: <span id="strength_percent">0</span>%</div>
<progress id="strength_progress" max="100" value="0"></progress>
</div>
<div id="errors"></div>
const validations = [
{
test: val => val.length >= 8,
message: 'пароль должен содержать хотя бы 8 символов',
},
{
test: val => /[A-ZА-ЯЁ]/.test(val),
message: 'пароль должен содержать хотя бы 1 большую букву',
},
{
test: val => /[a-zа-яё]/.test(val),
message: 'пароль должен содержать хотя бы 1 маленькую букву',
},
{
test: val => /[^\s\da-zа-яё]/i.test(val),
message: 'пароль должен содержать хотя бы 1 специальный символ (не пробел, букву или цифру)',
},
{
test: val => /\d/.test(val),
message: 'пароль должен содержать хотя бы 1 цифру',
},
];
document.querySelector('#password').addEventListener('input', ({ target: { value } }) => {
const errors = validations.reduce((acc, n) => (
n.test(value) || acc.push(n.message),
acc
), []);
const strength = (validations.length - errors.length) / validations.length * 100;
document.querySelector('#strength_progress').value = strength;
document.querySelector('#strength_percent').innerText = strength | 0;
document.querySelector('#errors').innerHTML = errors
.map(n => `<p>${n}</p>`)
.join('');
});