const inputSelector = '#kmOutMKAD';
const radioSelector = '[name="delivery"]';
const disabledValue = '1';
$(radioSelector).on('change', function() {
$(inputSelector).prop('disabled', this.value === disabledValue);
});
// или
const input = document.querySelector(inputSelector);
const radios = document.querySelectorAll(radioSelector);
const onChange = e => input.disabled = e.target.value === disabledValue;
radios.forEach(n => n.addEventListener('change', onChange));
const { classList: cl } = document.querySelector('#overlay');
const activeMenuClass = 'show-menu';
const matches = (el, ...selectors) => selectors.some(n => el.matches(n));
document.addEventListener('click', ({ target: t }) => {
if (matches(t, '#close-menu', 'li > a')) {
cl.remove(activeMenuClass);
} else if (matches(t, '#open-menu')) {
cl.add(activeMenuClass);
}
});
const
text = 'Sport',
str = 'port';
console.log(text.replace(new RegExp(`(${str})`, 'g'), '#$1#'));
или есть что-то оптимальней ?
text.replace(str, `#${str}#`)
. Правда, в отличие от регулярки - множественную замену так сделать не получится. const caesar = (str, offset) => Array
.from(str, n => String.fromCharCode(n.charCodeAt(0) + offset))
.join('');
const caesarTemplate = (title, offset) => `
<div class="caesar">
<textarea class="caesar-input" data-offset="${offset}"></textarea>
<hr>
<p>${title}: <span class="caesar-output"></span></p>
</div>
`;
document.addEventListener('input', ({ target: t }) => {
if (t.matches('.caesar-input')) {
const output = t.closest('.caesar').querySelector('.caesar-output');
output.innerHTML = caesar(t.value, +t.dataset.offset);
}
});
document.body.insertAdjacentHTML('beforeend', [
[ 'Шифр', 3 ],
[ 'Расшифровка', -3 ],
].map(n => caesarTemplate(...n)).join(''));
const text = (el => (el.innerHTML = html, el.innerText))(document.createElement('div'));
const text = new DOMParser().parseFromString(html, 'text/html').body.textContent;
const fragment = document.createRange().createContextualFragment(html);
const iter = document.createNodeIterator(fragment, NodeFilter.SHOW_TEXT);
const texts = [];
for (let n; n = iter.nextNode(); texts.push(n.nodeValue)) ;
<span class="prev" data-step="-1">Prev</span>
<span class="next" data-step="+1">Next</span>
eq
позволяет указывать отрицательные индексы, которые используются для отсчёта позиции элемента начиная с конца; в случае чистого js надо будет добавить к сумме количество элементов, чтобы потенциальное отрицательное значение стало положительным, и при этом не изменился остаток от деления.const itemSelector = 'li';
const buttonSelector = '[data-step]';
const activeClass = 'active';
$(buttonSelector).click(function() {
const { step } = this.dataset;
const $items = $(itemSelector);
const $active = $items.filter(`.${activeClass}`);
$active.removeClass(activeClass);
$items.eq(($active.index() + +step) % $items.length).addClass(activeClass);
});
// или
const items = document.querySelectorAll(itemSelector);
let index = 0;
document.querySelectorAll(buttonSelector).forEach(n => {
n.addEventListener('click', onClick);
});
function onClick({ currentTarget: { dataset: { step } } }) {
items[index].classList.remove(activeClass);
index = (index + items.length + +step) % items.length;
items[index].classList.add(activeClass);
}
Math.min
или перебираем вручную и сравниваем):const minDigit = num =>
Number.isFinite(num)
? Math.min(...`${num}`.replace(/\D/g, ''))
: null;
// или
const minDigit = num =>
(String(num).match(/\d/g) || []).reduce((min, n) => {
return min === null || n < min ? +n : min;
}, null);
minDigit(1) // 1
minDigit(759486394) // 3
minDigit(-56.209) // 0
minDigit(Infinity) // null
minDigit(NaN) // null
minDigit('hello, world!!') // null
li
на его же текст:$('.breadcrumb').children().last().text((i, text) => text);
// или
document.querySelector('.breadcrumb').lastElementChild.innerText += '';
a
есть элементы, они не будут удалены):$('.breadcrumb > :last > *').replaceWith((i, html) => html);
// или
(el => el.replaceWith(...el.childNodes))
(document.querySelector('.breadcrumb > :last-child > *'));
const containerSelector = 'ul';
const buttonSelector = 'a';
const elementSelector = '.drop';
const $el = $(elementSelector);
$(containerSelector).on('click', buttonSelector, function(e) {
$(e.currentTarget).after($el);
// или
$(this).parent().append($el);
// или
$el.insertAfter(this);
});
const el = document.querySelector(elementSelector);
document.querySelector(containerSelector).addEventListener('click', ({ target: t }) => {
if (t = t.closest(buttonSelector)) {
t.after(el);
// или
t.insertAdjacentElement('afterend', el);
// или
t.parentNode.insertBefore(el, t.nextSibling);
// или
t.parentNode.append(el);
// или
t.parentNode.appendChild(el);
}
});
words.replace(index, 1, word.charAt(0));
replace
у массивов нет. Есть splice
.как реализовали бы данную задачу вы?
const newWords = words.flatMap(RegExp.prototype.exec.bind(/.{0,1}/));
// или
const newWords = [];
for (const n of words) {
newWords.push(n[0] || '');
}
// или
const newWords = (function get(i, n = words[i]) {
return n != null ? [ n.slice(0, 1), ...get(-~i) ] : [];
})(0);
words.forEach(([ n = '' ], i, a) => a[i] = n);
// или
words.splice(0, words.length, ...words.map(n => n.charAt()));
// или
for (let i = 0; i < words.length; i++) {
words[i] = words[i].replace(/(?<=.).+/, '');
}
const $form = $('.order__form-contacts').on('change', '[name="legal-status"]', e => {
$form.find('.order__form-file')[e.target.value === '2' ? 'slideDown' : 'slideUp']();
});
arr1.forEach(function({ id }) {
if (this[id]) {
this[id].isAdded = true;
}
}, arr2.reduce((acc, n) => (acc[n.id] = n, acc), {}));
const newArr2 = arr2.map(function({ ...n }) {
if (this.has(n.id)) {
n.isAdded = true;
}
return n;
}, new Set(arr1.map(n => n.id)));
const text = 'определённый текст';
const link = document.querySelector(`a[href*="${text}"]`);
if (link) {
link.click();
}
.click()
на [0].click()
или .get(0).click()
.