const data = $('.price')
.filter((i, n) => +n.value)
.closest('tr')
.find('input[type="hidden"]')
.get()
.map(n => n.value);
const data = Array
.from(document.querySelectorAll('.price'))
.filter(n => +n.value)
.map(n => n.closest('tr').querySelector('input[type="hidden"]').value);
const data = Array.prototype.reduce.call(
document.getElementsByClassName('price'),
(acc, { value: v, parentNode: { parentNode: tr } }) => (
+v && acc.push(tr.cells[0].children[0].value),
acc
),
[]
);
когда оба поля заполнены нулями, необходимо выводить всю таблицу
(!min && !max)
. function setNestedValue(root, ...args) {
const val = args.pop();
const key = (args = args.join('.').split('.')).pop();
args.reduce((p, c) => p[c] = p[c] || {}, root)[key] = val;
}
const obj = {};
setNestedValue(obj, 'xxx', 'yyy', 'zzz', 69);
setNestedValue(obj, 'xxx.a.b.c', 187);
setNestedValue(obj, '_', 666);
Не могу понять как правильно написать цикл перебора.
$('.hello').attr('data-class', function() {
return [...this.classList].filter(n => n !== 'hello');
});
document.querySelectorAll('.hello').forEach(n => {
n.dataset.class = n.className.replace(/(^| )hello( | $)/, ' ').trim();
});
$('.hello').attr('data-class', function() {
return this.classList[1];
});
document.querySelectorAll('.hello').forEach(n => {
n.dataset.class = n.className.split(' ').pop();
});
Array.prototype.push.apply(
arr,
newArr.filter(n => !arr.some(m => m.trade_id === n.trade_id))
);
const pushDiff = (target, source, key = n => n) =>
target.push(...source.filter(function(n) {
return !this.has(key(n));
}, new Set(target.map(key))));
pushDiff(arr, newArr, n => n.trade_id);
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));
overlay.addEventListener('click', function(e) {
if ([ '#close-menu', 'li > a' ].some(n => e.target.matches(n))) {
overlay.classList.remove('show-menu');
}
});
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);
}