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;
}
const first = document.querySelector('.listing');
const tag = 'p';
const arr = [...'ABCDEF'];first.after(...arr.map(n => {
const el = document.createElement(tag);
el.textContent = n;
return el;
}));
// или
first.replaceWith(first, ...arr.reduce((acc, n, i) => (
(acc[i] = document.createElement(tag)).innerText = n,
acc
), []));
// или
arr.reduce((prev, n) => (
prev.insertAdjacentElement('afterend', document.createElement(tag)),
prev.nextSibling.append(n),
prev.nextSibling
), first);
// или
const parent = first.parentNode;
const nodes = parent.childNodes;
arr.forEach(function(n) {
const el = document.createElement(tag);
el.appendChild(new Text(n));
parent.insertBefore(el, nodes[++this[0]]);
}, [ Array.prototype.indexOf.call(nodes, first) ]);
// или
first.insertAdjacentHTML(
'afterend',
arr.map(n => `<${tag}>${n}</${tag}>`).join('')
);
$('table').on('change', 'select', ({ target: t }) => {
$(t).replaceWith(t.value);
// или
$(t).prop('outerText', t.value);
// или
$(t).after(t.value).remove();
});const isSelect = el => el.tagName === 'SELECT';
// или
const isSelect = el => el.nodeName === 'SELECT';
// или
const isSelect = el => el.matches('select');
// или
const isSelect = el => el instanceof HTMLSelectElement;document.querySelector('table').addEventListener('change', ({ target: t }) => {
if (isSelect(t)) {
t.replaceWith(t.value);
// или
t.parentNode.replaceChild(new Text(t.value), t);
// или
t.outerText = t.value;
// или
t.after(t.value);
t.remove();
// или
t.parentNode.replaceChildren(...Array.from(
t.parentNode.childNodes,
n => n === t ? t.value : n
));
}
});
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 = 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);
}, 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)));
// или
Object
.values(arr.reduce((acc, n, i) => ((acc[n] ??= []).push(i), acc), {}))
.forEach(n => n.forEach(i => arr[i] = n.length > 1));
$('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.toLowerCase().includes(val)
? 'block'
: 'none';
});
});document.getElementById('filter-input').oninput = function() {
const val = this.value.toLowerCase();
for (const n of container.getElementsByClassName('title')) {
let card = n;
while (!(card = card.parentNode).classList.contains('card')) ;
card.hidden = n.textContent.toLowerCase().indexOf(val) === -1;
}
};
const key = 'answer';.const obj = Object.fromEntries(arr.map((n, i) => [ `${key}${i + 1}`, n ]));const obj = arr.reduce((acc, n, i) => (acc[key + ++i] = n, acc), {});const obj = {};
for (const [ i, n ] of arr.entries()) {
obj[key.concat(-~i)] = n;
}const obj = (function get(arr) {
const i = arr.length;
const n = arr.pop();
return i
? { ...get(arr), [[ key, i ].join``]: n }
: {};
})([...arr]);
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', e => {
const errors = validations.reduce((acc, n) => (
n.test(e.target.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('');
});
оборачивается не полностью
childNodes представляет собой динамическую коллекцию, т.е., при добавлении или удалении узлов она обновляется без каких-либо действий с вашей стороны. Поэтому, когда вы добавляете в wrapper нулевой узел, он тут же пропадает из item.childNodes, а у оставшихся узлов позиция уменьшается на единицу - тот, что был первым, становится нулевым, второй первым и так далее. Так что когда for...of переходит к следующему узлу, им оказывается не тот, что изначально имел индекс 1, а расположенный за ним. Бывший первый, а теперь нулевой, оказывается пропущен. Аналогичным образом будут пропущены и все последующие узлы, изначально имевшие нечётные индексы.for (let n; n = item.firstChild;) {
wrapper.appendChild(n);
}childNodes от конца к началу:for (let i = item.childNodes.length; i--;) {
wrapper.prepend(item.childNodes[i]);
}childNodes, а массив:for (const n of [...item.childNodes]) {
wrapper.insertBefore(n, null);
}append может принимать несколько параметров, так что переносим сразу всё:document.querySelectorAll('.www').forEach(n => {
const wrapper = document.createElement('div');
wrapper.classList.add('red');
wrapper.append(...n.childNodes);
n.append(wrapper);
});for (const n of document.getElementsByClassName('www')) {
n.innerHTML = `<div class="red">${n.innerHTML}</div>`;
}
const sorted = arr
.map(n => [
n,
+new URLSearchParams(n.querySelector('a').href.split('?').pop()).get('value') || Infinity,
])
.sort((a, b) => a[1] - b[1])
.map(n => n[0]);parentEl.append(...Array
.from(parentEl.querySelectorAll('a'), n => [
n.parentNode,
Number(n.getAttribute('href').match(/(?<=value=)\d+/)) || Infinity,
])
.sort((a, b) => a[1] - b[1])
.map(n => n[0])
);
const updateValue = input =>
input.previousElementSibling.querySelector('.p_value').innerText = input.value;class="xxx".document.addEventListener('input', ({ target: t }) => {
if (t.classList.contains('xxx')) {
updateValue(t);
}
});document.querySelectorAll('.xxx').forEach(function(n) {
n.addEventListener('input', this);
}, e => updateValue(e.target));
const cols = document.querySelectorAll('.col');
cols.forEach(n => {
n.addEventListener('mouseover', onHover);
n.addEventListener('mouseout', onHover);
});
function onHover(e) {
const index = [...this.children].findIndex(n => n.contains(e.target));
if (index !== -1) {
const t = e.type === 'mouseover';
cols.forEach(n => n.children[index].classList.toggle('hovered', t));
}
}
const links = document.querySelectorAll('.nav-about a');links.forEach((n, i) => n.attributes.href.value += i + 1);
// или
for (const [ i, n ] of links.entries()) {
n.setAttribute('href', n.getAttribute('href').concat(-~i));
}
// или
for (let i = 0; i < links.length;) {
links[i].href = links[i].href.replace(/.*(#.*)/, `$1${++i}`);
}
$('button').click(() => $('select').prop('selectedIndex', 0));document.querySelector('button').addEventListener('click', () => {
document.querySelectorAll('select').forEach(n => {
// Какие тут есть варианты:
// 1. Установить индекс выбранного option'а
n.selectedIndex = 0;
// 2. Установить select'у значение option'а, который должен быть выбран
// (чтобы заработало, надо будет добавить value="" option'ам)
n.value = '';
// 3. Назначить true свойству selected того option'а, на который надо переключиться
n[0].selected = true;
// или
// n.options[0].selected = true;
// n.children[0].selected = true;
// n.firstElementChild.selected = true;
// n.querySelector('option').selected = true;
});
});
const arrs = [ arr1, arr2 ];), дальше есть варианты:const result = arrs[0].map((_, i) => arrs.flatMap(arr => arr[i]));const result = arrs.reduce((acc, arr) => (
arr.forEach((n, i) => (acc[i] ??= []).push(...n)),
acc
), []);const result = [];
for (const arr of arrs) {
for (const [ i, n ] of arr.entries()) {
if (!result[i]) {
result[i] = [];
}
for (const m of n) {
result[i][result[i].length] = m;
}
}
}function* zip(data, defaultValue = null) {
const iterators = Array.from(data, n => n[Symbol.iterator]());
for (let doneAll = false; doneAll = !doneAll;) {
const values = [];
for (const n of iterators) {
const { value, done } = n.next();
values.push(done ? defaultValue : value);
doneAll &&= done;
}
if (!doneAll) {
yield values;
}
}
}
const result = Array.from(zip(arrs), n => n.flat());