const checkedTexts = (el, selector) =>
Array.from(el.querySelectorAll(`${selector}:checked`), n => n.parentNode.innerText);
const propertyText = (el, selector) =>
el.querySelector(selector).innerText.split(': ')[1];
document.querySelector('.container-filter').addEventListener('input', function() {
const maxPrice = parseInt(this.querySelector('.range').value);
const brands = checkedTexts(this, '.input');
const years = checkedTexts(this, '.input-date');
document.querySelectorAll('.device .laptop').forEach(n => {
const price = parseInt(propertyText(n, '.laptop-price'));
const brand = propertyText(n, '.laptop-name');
const year = propertyText(n, '.laptop-year');
n.style.display = (
(maxPrice >= price) &&
(!brands.length || brands.includes(brand)) &&
(!years.length || years.includes(year))
)
? 'block'
: 'none';
});
});
const newStr = str
.split(' ')
.map(function([...word]) {
const sorted = word.filter(this).sort((a, b) => b.localeCompare(a));
return word.map(n => this(n) ? sorted.pop() : n).join('');
}, RegExp.prototype.test.bind(/[a-z]/i))
.join(' ');
str.replace(/(\d{2})(\d{2})/, '$1.$2.')
// или
str.replace(/(?=\d{4}$|\d{6}$)/g, '.')
// или
str.match(/(..)(..)(.+)/).slice(1).join('.')
// или
[ 0, 2, 4 ].map((n, i, a) => str.slice(n, a[i + 1])).join`.`
// или
[...str].reduce((acc, n, i) => acc + n + ([ ,'.',,'.' ][i] || ''))
// или
''.concat(...Array.from(str, (n, i) => '24'.includes(i) ? `.${n}` : n))
const buttons = document.querySelector('.content');
const blocks = document.querySelector('.wrap');
const key = 'block';
const attr = `data-${key}`;
const attrSelector = `[${attr}]`;
buttons.addEventListener('click', e => {
const button = e.target.closest(attrSelector);
if (button) {
const value = button.dataset[key];
console.log(blocks.querySelectorAll(`[${attr}="${value}"]`).length);
}
});
const onClick = ({ currentTarget: { attributes: { [attr]: { value } } } }) =>
console.log(Array.prototype.reduce.call(
blocks.children,
(acc, n) => acc + (n.getAttribute(attr) === value),
0
));
for (const n of buttons.children) {
n.addEventListener('click', onClick);
}
document.querySelector('table').addEventListener('click', ({ target: t }) => {
if (t.classList.contains('save_order')) {
const tr = t.closest('tr');
console.log(tr);
}
// или
if (t.matches('.save_order')) {
let tr = t;
while ((tr = tr.parentNode).tagName !== 'TR') ;
console.log(tr);
}
});
arr.pop();
// или
arr.length -= !!arr.length;
// или
arr.splice(-1);
const count = сколько надо удалить;
):for (let i = count; --i >= 0 && arr.length; arr.pop()) ;
// или
arr.length -= Math.max(0, Math.min(arr.length, count));
// или
count > 0 && arr.splice(-count);
document.addEventListener('input', ({ target: t }) => {
if (t.classList.contains('rating__value')) {
const value = +t.value;
t.closest('.item-rating').querySelector('.rating__dynamic').innerHTML = Array
.from({ length: 5 }, (n, i) => `<span class="char">${'☆★'[+(value > i)]}</span>`)
.join('');
}
});
document.querySelectorAll('.rating__value').forEach(n => {
n.dispatchEvent(new Event('input', { bubbles: true }));
});
for (const n of document.getElementsByClassName('rating__value')) {
n.previousElementSibling.innerHTML = '<span class="char"></span>'.repeat(5);
n.addEventListener('input', onRatingInput);
onRatingInput.call(n);
}
function onRatingInput() {
const value = this.value | 0;
const stars = this.previousElementSibling.children;
for (let i = 0; i < stars.length; i++) {
stars[i].innerText = value > i ? '★' : '☆';
}
}
const listTag = 'ul';
const listClass = 'list';
const itemTag = 'li';
const itemClass = 'item';
const activeClass = 'active';
const list = document.createElement(listTag);
const items = arr.map(function(n) {
const item = document.createElement(itemTag);
item.textContent = n.text;
item.classList.add(itemClass);
item.addEventListener('click', this);
return item;
}, function() {
list.style.setProperty('background-image', `url(${arr[items.indexOf(this)].url})`);
items.forEach(n => n.classList.toggle(activeClass, n === this));
});
list.classList.add(listClass);
list.append(...items);
document.body.append(list);
items[0].click();
document.body.insertAdjacentHTML('beforeend', `
<${listTag} class="${listClass}">${arr.map(({ url, text }) => `
<${itemTag} class="${itemClass}" data-url="${url}">${text}</${itemTag}>`).join``}
</${listTag}>
`);
const list = document.body.lastElementChild;
list.addEventListener('click', ({ target: t }) => {
if (t = t.closest(`${itemTag}.${itemClass}`)) {
list.style.backgroundImage = `url(${t.dataset.url})`;
list.querySelector(`.${activeClass}`)?.classList.remove(activeClass);
t.classList.add(activeClass);
}
});
list.children[0].dispatchEvent(new Event('click', { bubbles: true }));
const sorted = (arr, key) => arr
.map(n => [ key(n), n ])
.sort(([a], [b]) => a < b ? -1 : +(a > b))
.map(n => n[1]);
const sortedArr = sorted(
arr,
n => new Date(n.date.replace(/(\d+)\.(\d+)\.(\d+)/, '$3-$2-$1'))
);
// или
const sortedArr = sorted(
arr,
n => n.date.replace(/[^T]+/, m => m.split('.').reverse().join(''))
);
button с классами .tool и .название цвета
let color = '#000';
document.querySelector('селектор контейнера с кнопками').addEventListener('click', e => {
if (e.target.classList.contains('tool')) {
color = e.target.dataset.color;
}
});
document.querySelector('селектор контейнера с "пикселями"').addEventListener('click', e => {
if (e.target.classList.contains('pixel')) {
e.target.style.backgroundColor = color;
}
});
filterBox.forEach(n => {
n.classList.toggle('none', ![ 'all', n.dataset.work ].includes(filterBtn));
});
const container = document.querySelector('.side__nav');
const itemSelector = 'li';
const activeClass = 'is-active';
container.addEventListener('click', function(e) {
const item = e.target.closest(itemSelector);
if (item) {
this.querySelector(`${itemSelector}.${activeClass}`)?.classList.remove(activeClass);
item.classList.add(activeClass);
}
});
const items = container.querySelectorAll(itemSelector);
const onClick = e => items.forEach(n => n.classList.toggle(activeClass, n === e.currentTarget));
items.forEach(n => n.addEventListener('click', onClick));
const element = document.querySelector(`.js-filter-wrap a[data-filter="${конкретноеЗначение}"]`);
if (element) {
...
const element = [...elements].find(n => n.dataset.filter === конкретноеЗначение);
if (element) {
...
Internal methods and internal slots are identified within this specification using names enclosed in double square brackets...
Within this specification a well-known symbol is referred to by using a notation of the form @@name...
Within this specification a reference such as %name% means the intrinsic object...
let displayMessage = ''; doItems.forEach((item, i) => { displayMessage += ` <li class="do__item"> <input type="checkbox" id="do_${i}" ${item.checked ? 'checked': ' '}> <label for="do_${i}" class="${item.checked ? 'checked' : ' '}">${item.message}</label> <button class="remove" id="do_${i}">Delete</button> </li>`; block.innerHTML = displayMessage; });
const insert = (str, index, substr) =>
str.replace(RegExp(`(?<=.{${index}})`), substr);
// или
const insert = (str, index, substr) =>
str.replace(RegExp(`.{${index}}`), `$&${substr}`);
// или
const insert = (str, index, substr) =>
str.length >= index ? str.slice(0, index) + substr + str.slice(index) : str;