const elements = document.querySelectorAll('input[type="button"]');
const tag = 'div';
const className = 'block';elements.forEach(n => {
n.after(document.createElement(tag));
n.nextSibling.className = className;
n.nextSibling.append(n);
});for (const n of elements) {
const wrapper = document.createElement(tag);
wrapper.classList.add(className);
wrapper.appendChild(n.parentNode.replaceChild(wrapper, n));
}for (let i = 0; i < elements.length; i++) {
const wrapper = document.createElement(tag);
elements[i].replaceWith(wrapper);
wrapper.classList.value = className;
wrapper.insertAdjacentElement('afterbegin', elements[i]);
}(function wrap(i, n = elements.item(i)) {
if (n) {
n.outerHTML = `<${tag} class="${className}">${n.outerHTML}</${tag}>`;
wrap(-~i);
}
})(0);
const select = document.querySelector('вам виднее, что тут должно быть');
const values = [ '1', '2', '3' ];[...select].forEach(n => values.includes(n.value) && n.remove());for (const n of select.querySelectorAll(values.map(n => `[value="${n}"]`))) {
select.removeChild(n);
}select.replaceChildren(...Array.prototype.filter.call(
select,
((values, n) => !values.has(n.value)).bind(null, new Set(values))
));Array.prototype.reduceRight.call(
select.options,
(_, n) => ~values.indexOf(n.value) && n.replaceWith(),
null
);select.innerHTML = Array
.from(select.children)
.filter(function(n) {
return n.matches(this);
}, `:not(${values.map(n => `[value="${n}"]`)})`)
.map(n => n.outerHTML)
.join('');(function next(i, n = select.item(--i)) {
if (n) {
for (const v of values) {
if (v === n.value) {
n.outerHTML = '';
break;
}
}
next(i);
}
})(select.length);
calc__price и calc__payment заменить на общий calc.const $price = $('#price');
const $firstPayment = $('#first-payment');
function update($elem) {
$elem.closest('.calc').find('output').text($elem.val());
$('.payment-percent').html(Math.round($firstPayment.val() * 100 / $price.val()) + '%');
}
$price.closest('.calc').on('input', function() {
const val = $price.val();
$firstPayment
.val((i, v) => Math.min(v, val))
.attr('max', val)
.rangeslider('update', true);
update($firstPayment);
});
$price.add($firstPayment)
.rangeslider({ polyfill: false })
.closest('.calc')
.on('input', e => update($(e.target)))
.end()
.trigger('input');
function walkNested(val, callback) {
callback(val);
if (val instanceof Object) {
Object.values(val).forEach(n => walkNested(n, callback));
}
}function walkNested(val, callback) {
for (const stack = [ val ]; stack.length;) {
const n = stack.pop();
callback(n);
if (n instanceof Object) {
stack.push(...Object.values(n));
}
}
}walkNested(obj, n => n?.touched === true && (n.touched = false));
const keys = [ 'city', 'country' ];.const newArr = arr.map(n => Object.fromEntries(Object.values(n).map((v, i) => [ keys[i], v ])));arr.forEach(n => Object.entries(n).forEach(([ k, v ], i) => (delete n[k], n[keys[i]] = v)));
str.replace(/\t.*/s, '')
// или
str.match(/^[^\t]*/)[0]
// или
str.slice(0, str.search(/\t|$/))
// или
str.split('\t', 1).pop()
// или
[...str].reduceRight((acc, n) => n === '\t' ? '' : n + acc, '')
const sourceSelector = '#menu a';
const targetSelector = '#submenu > ul';$source = $(sourceSelector);
$(targetSelector).width(i => $source.eq(i).width());
// или
document.querySelectorAll(targetSelector).forEach(function(n, i) {
n.style.width = `${this[i].offsetWidth}px`;
}, document.querySelectorAll(sourceSelector));
const min = 7;
const max = min + 21;
function update(value) {
value = Math.max(min, Math.min(max, value | 0));
$('#spinner2').val(value);
$('#slider2').slider('value', value);
const date = new Date();
date.setDate(date.getDate() + value);
$('#amount').val(date.toLocaleString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
}));
}
$('#slider2').slider({
range: 'min',
min,
max,
step: 1,
slide: (e, ui) => update(ui.value),
});
$('#spinner2').spinner({
min,
max,
spin: (e, ui) => update(ui.value),
}).on('input', e => update(e.target.value)).trigger('input');
const sort = {
number: (a, b) => a - b,
string: (a, b) => a.localeCompare(b),
};function sortTable(table, colIndex) {
if (typeof table === 'string') {
table = document.querySelector(table);
}
const head = table.tHead.rows[0];
const compare = sort[head.cells[colIndex].dataset.type] ?? sort.string;
const value = row => row.cells[colIndex].innerText;
const tbody = table.tBodies[0];
tbody.append(...[...tbody.rows].sort((a, b) => compare(value(a), value(b))));
[...head.cells].forEach((n, i) => n.classList.toggle('sorted', i == colIndex));
}.sorted {
background: #ccc;
}
.sorted::after {
content: " \2193";
}// просто дёргаем сортировку
sortTable('#grid', 0);
sortTable(document.querySelector('table'), 1);
// или, сортируем по клику на заголовки столбцов
document.querySelectorAll('#grid th').forEach(function(n) {
n.addEventListener('click', this);
}, ({ target: t }) => sortTable(t.closest('table'), t.cellIndex));
<div class="phone">8 (123) 111-22-33</div>
<div class="phone">8 (456) 444-55-66</div>
<div class="phone">8 (789) 777-88-99</div>document.querySelectorAll('.phone').forEach(n => {
const phone = n.innerHTML;
n.innerHTML = phone.slice(0, -4) + '... - <span>показать</span>';
n.querySelector('span').addEventListener('click', () => n.innerHTML = phone);
});
function filter(val) {
if (!(val instanceof Object)) {
return val;
}
const filtered = Object
.entries(val)
.map(n => [ n[0], filter(n[1]) ])
.filter(n => n[1]);
return filtered.length
? val instanceof Array
? filtered.map(n => n[1])
: Object.fromEntries(filtered)
: null;
}
const elements = document.querySelectorAll('.price');
const output = document.querySelector('.min-sum');output.textContent = Math.min(...Array.from(
elements,
n => parseFloat(n.textContent)
));
// или
output.innerText = Array.prototype.reduce.call(
elements,
(min, n) => (
n = +n.innerText.match(/[\d.]+/),
n < min ? n : min
),
Infinity
);
const parent = document.querySelector('ul');
const selector = '#elem';const elem = parent.querySelector(selector)?.nextElementSibling;
if (elem) {
const num = 1 + Array.prototype.indexOf.call(parent.children, elem);
elem.textContent = num + '. ' + elem.textContent;
}const elem = parent.querySelector(`${selector} + *`);
if (elem) {
let num = 1;
for (let n = elem; n = n.previousElementSibling; num++) ;
elem.insertAdjacentText('afterbegin', `${num}. `);
}const index = -~[...parent.children].findIndex(n => n.matches(selector));
if (index) {
parent.children[index]?.prepend(''.concat(-~index, '. '));
}
Как наиболее короче сделать...
generalDiv.innerHTML = newCats
.filter(n => n?.breeds.length)
.map(({ url, breeds: [ b ] }) => `
<div class="cat__item">
<div class="cat__img"><img src="${url}" alt="${b.name}"></div>
<div class="cat__name">${b.name}</div>
<div class="cat__temperament">${b.temperament}</div>
<div class="cat__live">${b.life_span}</div>
<div class="cat__origin">${b.origin}</div>
<div class="cat__description">${b.description}</div>
<div class="cat__wikipedia_url">${b.wikipedia_url}</div>
</div>
`)
.join('');
document.querySelector('form').addEventListener('change', e => {
const sum = Array.prototype.reduce.call(
e.currentTarget.querySelectorAll('input:checked'),
(acc, n) => acc + +n.value,
0
);
document.querySelector('#pSumma').innerText = `$${sum.toFixed(2)}`;
});
document.querySelectorAll('.g-project__words-moving').forEach(n => {
const html = n.querySelector('.words-moving__calm span').outerHTML.repeat(10);
n.querySelectorAll('.running-string-wrapp').forEach(m => m.innerHTML = html);
});.words-moving__calm span, вместо того, чтобы ограничиться только теми, которые лежат внутри текущего элемента .g-project__words-moving. Для исправления можно перенести объявление place в начало тела внешнего цикла, заменив при этом document на boxes[i].
Array.prototype.push.apply(
arr,
newArr.filter(n => !arr.some(m => m.id === n.id))
);arr.splice(0, arr.length, ...arr
.concat(newArr)
.reduce((acc, n) => acc.set(n.id, acc.get(n.id) ?? n), new Map)
.values()
);newArr.forEach(function(n) {
this.has(n.id) || (arr[arr.length] = n);
}, new Set(arr.map(n => n.id)));