Object.entries(obj).filter(n => Number.isInteger(+n[0])).map(n => n[1]).join(';')
// или
Object.keys(obj).reduce((acc, n) => (`${+n}` === n && acc.push(obj[n]), acc), []).join(';')
// или
Array.from(obj).join(';')
// или
JSON.stringify(obj).match(/(?<="\d+":").*?(?=")/g).join(';')
$('.open-category').click(function() {
$(`.d-none[data-id="${this.dataset.id}"]`).toggleClass('active');
});
for (const n of document.getElementsByClassName('open-category')) {
n.addEventListener('click', onClick);
}
function onClick({ target: { dataset: { id } } }) {
document.querySelector(`.d-none[data-id="${id}"]`).classList.toggle('active');
}
const elements = new Map(Array.from(
document.querySelectorAll('.open-category'),
n => [ n, document.querySelector(`.d-none[data-id="${n.dataset.id}"]`) ]
));
document.addEventListener('click', e => {
elements.get(e.target)?.classList.toggle('active');
});
идет смещение индексов, но как это обойти, уже не знаю
for (let i = arr.length; i--;) {
invItems.splice(arr[i], 1);
}
for (const n of [...arr].reverse()) {
invItems.splice(n, 1);
}
for (const [ i, n ] of arr.entries()) {
invItems.splice(n - i, 1);
}
invItems.splice(0, invItems.length, ...invItems.filter((n, i) => !arr.includes(i)));
let numDeleted = 0;
for (let i = 0; i < invItems.length; i++) {
invItems[i - numDeleted] = invItems[i];
numDeleted += i === arr[numDeleted];
}
invItems.length -= numDeleted;
async function fetchRecursive(arr) {
const result = [];
if (Array.isArray(arr)) {
for (const n of arr) {
try {
result.push({ status: true, result: await fetch(n.url).then(r => r.json()) });
} catch(error) {
result.push({ status: false, error });
}
result.push(...await fetchRecursive(n.children));
}
}
return result;
}
const flat = arr => (arr || []).flatMap(n => [ n.url, ...flat(n.children) ]);
const fetchRecursive = arr => Promise.allSettled(flat(arr).map(n => fetch(n).then(r => r.json())));
<div class="comment" data-id="187">
<a class="comment-edit">Редактировать</a>
<span class="comment-panel"></span>
</div>
.comment .comment-panel {
display: none;
}
.comment.editing .comment-panel {
display: inline;
}
.comment.editing .comment-edit {
color: red;
}
const containerSelector = '.comment';
const buttonSelector = '.comment-edit';
const activeClass = 'editing';
// вот вам ваш jquery
$(containerSelector).on('click', buttonSelector, e => {
const id = $(e.delegateTarget).toggleClass(activeClass).data('id');
console.log(id);
});
// или, к чёрту jquery
document
.querySelectorAll(`${containerSelector} ${buttonSelector}`)
.forEach(n => n.addEventListener('click', onClick));
function onClick() {
const container = this.closest(containerSelector);
container.classList.toggle(activeClass);
const { id } = container.dataset;
console.log(id);
}
document.querySelectorAll('.class-1').forEach(n => {
n.insertAdjacentHTML('afterbegin', `<div>${n.querySelector('span').dataset.name}</div>`);
});
$('.class-1').prepend(function() {
return $('<div>').text($('span', this).data('name'));
});
function codeAddress(address, geocoder, map) {
geocoder.geocode({ address }, function(results, status) {
if (status === 'OK') {
new google.maps.Marker({
map: map,
position: results[0].geometry.location,
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
address.forEach(n => codeAddress(n, geocoder, map));
$('.list-item').filter((i, n) => $(n).data('pagereview') !== $(n).data('pageslug')).hide();
$('[data-pageslug]').each(function() {
const $this = $(this);
$this.toggle($this.attr('data-pagereview') === $this.attr('data-pageslug'));
});
document.querySelectorAll('.list-item').forEach(n => {
n.hidden = n.getAttribute('data-pagereview') !== n.getAttribute('data-pageslug');
});
for (const { style, dataset } of document.getElementsByClassName('list-item')) {
if (dataset.pagereview !== dataset.pageslug) {
style.display = 'none';
}
}
.hidden {
display: none;
}
const items = document.querySelectorAll('[data-pageslug]');
for (let i = 0; i < items.length; i++) {
const { classList: c, attributes: a } = items[i];
c.toggle('hidden', a['data-pagereview'].value !== a['data-pageslug'].value);
}
$('.price_min_max_btn').click(function() {
const min = +$('.price_min').val() || 0;
const max = +$('.price_max').val() || Infinity;
$('.item_block_filter')
.hide()
.filter(function() {
const price = +this.dataset.price;
return min <= price && price <= max;
})
.show();
});
document.querySelector('table').addEventListener('click', e => {
const td = e.target.closest('td');
if (td) {
const index = td.cellIndex;
console.log(index);
}
});
const arr = str.split('-');
const end = 'final';
const obj = arr.reduceRight((acc, n) => ({ [n]: acc }), end);
const obj = (function createObj(arr, i, end) {
return i < arr.length
? { [arr[i]]: createObj(arr, i + 1, end) }
: end;
})(arr, 0, end);
const result = graphData.map((n, i) => ({ ...n, color: palette[i % palette.length] }));
const combine = (arr, keys, values) =>
arr.map(({ ...n }, i) => (
values.forEach((m, j) => n[keys[j]] = m[i % m.length]),
n
));
const result = combine(graphData, [ 'color' ], [ palette ]);
// при клике по кнопке определяем её индекс и хватаем .photos__like-count с таким же индексом
document.addEventListener('click', ({ target: t }) => {
if (t.classList.contains('photos__like-icon')) {
const index = [...document.querySelectorAll('.photos__like-icon')].indexOf(t);
const counter = document.querySelectorAll('.photos__like-count')[index];
const count = counter.textContent;
counter.textContent = t.classList.toggle('active') ? -~count : ~-count;
}
});
// но если у каждой пары icon-count если отдельный общий предок, то можно и попроще сделать
document.addEventListener('click', ({ target: t }) => {
if (t.matches('.photos__like-icon')) {
t
.closest('селектор общего предка кнопки и элемента с количеством')
.querySelector('.photos__like-count')
.textContent -= t.classList.toggle('active') ? -1 : 1;
}
});
const toggleLike = function({ target: t }) {
this[t.dataset.index].innerText -= [ 1, -1 ][+t.classList.toggle('active')];
}.bind(document.querySelectorAll('.photos__like-count'));
document.querySelectorAll('.photos__like-icon').forEach((n, i) => {
n.dataset.index = i;
n.addEventListener('click', toggleLike);
});
// или, при наличии отдельных общих предков у каждой пары .photos__like-icon и .photos__like-count
const toggleLike = ({ target: t }) => t
.closest('селектор общего предка кнопки и элемента с количеством')
.querySelector('.photos__like-count')
.innerText -= t.classList.toggle('active') ? -1 : 1;
for (const n of document.querySelectorAll('.photos__like-icon')) {
n.addEventListener('click', toggleLike);
}
function setAnimation(el) {
$(el).css('animation', `shadow-pulse ${1 + Math.random() * 3}s`);
}
$('.mr-2').on('animationend', function() {
$(this).css('animation', '');
setTimeout(setAnimation, 0, this);
}).get().forEach(setAnimation);
$('.search').on('input', function() {
const search = $(this).val().trim().toLowerCase();
$('.metro-line__item')
.hide()
.filter((i, n) => $('.metro__name', n).text().toLowerCase().includes(search))
.show();
$('.metro-line')
.show()
.not(':has(.metro-line__item:visible)')
.hide();
});
.hidden {
display: none;
}
document.querySelector('.search').addEventListener('input', e => {
const search = e.target.value.trim().toLowerCase();
document.querySelectorAll('.metro-line__item').forEach(n => {
const name = n.querySelector('.metro__name').textContent.toLowerCase();
n.classList.toggle('hidden', !name.includes(search));
});
document.querySelectorAll('.metro-line').forEach(n => {
n.classList.toggle('hidden', !n.querySelector('.metro-line__item:not(.hidden)'));
});
});