document.addEventListener('keydown', e => {
if (e.key === 'Backspace' && e.target !== display) {
display.value = display.value.slice(0, -1);
// или
display.value = display.value.substring(0, display.value.length - 1);
// или
display.value = display.value.replace(/.$/, '');
// или
display.value = display.value.match(/.*(?=.$)/);
// или
display.value = [...display.value].filter((n, i, a) => -~i < a.length).join('');
}
});
$(document).click(function(e) {
if (!$panel.has(e.target).length && $panel.hasClass('visible')) {
hidePanel();
}
});
const ip = str.split(':', 1)[0];const ip = str.slice(0, str.indexOf(':'));const ip = str.match(/[\d.]+/).pop();const ip = str.replace(/:.+$/, '');const [ ip ] = /.+(?=:)/.exec(str);
const plainToNested = (source, target = {}) =>
Object.entries(source).reduce((acc, [ path, val ]) => {
const keys = path.split('.');
const key = keys.pop();
keys.reduce((p, c) => p[c] = p[c] || {}, acc)[key] = val;
return acc;
}, target);
const buttonSelector = '.one-click-button';
const key = 'id';
const attr = `data-${key}`;
const input = document.querySelector('#one_b_id');const getId = el => el.dataset[key];
// или
const getId = el => el.getAttribute(attr);
// или
const getId = el => el.attributes[attr].value;document.addEventListener('click', e => {
const button = e.target.closest(buttonSelector);
if (button) {
input.value = getId(button);
}
});document.querySelectorAll(buttonSelector).forEach(function(n) {
n.addEventListener('click', this);
}, e => input.value = getId(e.currentTarget));
Как я могу проверить на наличие в начале строки undefined и удалить её?
str.replace(/^undefined/, '').
divParent.insertBefore(elems[i].cloneNode(true), null);divParent.insertBefore(elems[i].cloneNode(true), divParent.firstChild);
// или
divParent.insertAdjacentElement('afterbegin', elems[i].cloneNode(true));
// или
divParent.prepend(elems[i].cloneNode(true));for (const n of document.getElementsByClassName('basic')) {
n.after(document.createElement('div'));
n.nextSibling.classList.add('parent');
n.nextSibling.append(document.createElement('b'));
n.nextSibling.lastChild.textContent = 'Важная строка';
n.nextSibling.prepend(n);
}document.querySelectorAll('.basic').forEach(n => {
const html = `
<div class="parent">
${n.outerHTML}
<b>Важная строка</b>
</div>
`;
n.outerHTML = html;
// или
n.insertAdjacentHTML('afterend', html);
n.remove();
// или
n.replaceWith(document.createRange().createContextualFragment(html));
// или
n.replaceWith(...new DOMParser().parseFromString(html, 'text/html').body.childNodes);
});
document.querySelectorAll('.number').forEach(function(n) {
const top = n.getBoundingClientRect().top;
const end = +n.dataset.max;
window.addEventListener('scroll', function onScroll() {
if (window.pageYOffset > top - window.innerHeight / 2) {
this.removeEventListener('scroll', onScroll);
let start = +n.innerHTML;
const interval = setInterval(function() {
n.innerHTML = ++start;
if (start === end) {
clearInterval(interval);
}
}, 5);
}
});
});
const max = Math.max(...Object.values(obj[0]).map(n => n ? n.level : -Infinity));
const objectParser = (data, path = '') =>
Object.assign(
{ [path || '<root>']: data },
...(data instanceof Object
? Object.entries(data).map(([ k, v ]) => objectParser(v, `${path}[${k}]`))
: []
)
);function objectParser(data) {
const result = {};
for (const stack = [ [ data, '' ] ]; stack.length;) {
const [ n, path ] = stack.pop();
result[path || '<root>'] = n;
(n instanceof Object) && Object
.entries(n)
.reverse()
.forEach(([ k, v ]) => stack.push([ v, `${path}[${k}]` ]));
}
return result;
}
const parentSelector = 'селектор родительского элемента';
const noClassSelector = 'селектор элементов, которым не надо добавлять класс';
const className = 'класс';$(parentSelector)
.children()
.removeClass(className)
.not(noClassSelector)
.addClass(className);
// или
for (const n of document.querySelector(parentSelector).children) {
n.classList.toggle(className, !n.matches(noClassSelector));
}
n < locals.length сделайте n < locals.length / 3.3 * n будет просто n, вместо 3 * n + 1 будет n + 1, и т.д.
const formatTime = seconds => [
seconds / 3600 | 0,
seconds / 60 % 60 | 0,
seconds % 60,
].map(n => `${n}`.padStart(2, 0)).join(':');
const LENGTH = чему-то там равно, это вам виднее;
const input = document.querySelector('селектор инпута');
const button = document.querySelector('селектор кнопки');
input.addEventListener('input', e => {
button.style.display = e.target.value.length >= LENGTH ? '' : 'none';
});
input.dispatchEvent(new Event('input'));
if (typeof defaultBg1 == 'Background') // ???null и undefined свойств не бывает, попытка обратиться к конструктору в их случае приведёт к TypeError; кроме того, instanceof проверяет всю цепочку прототипов, т.е., например, [ 1, 2, 3 ] одновременно и instanceof Array, и instanceof Object):if (defaultBg1 instanceof Background)
// или
if (defaultBg1.constructor === Background)
// или
if (defaultBg1.constructor.name === 'Background')const type = x => x == null ? `${x}` : x.constructor.name;
type() // 'undefined'
type(null) // 'null'
type(true) // 'Boolean'
type(69) // 'Number'
type('hello, world!!') // 'String'
type(/./) // 'RegExp'
type([ 187 ]) // 'Array'
type({ z: 666 }) // 'Object'
type(document) // 'HTMLDocument'
type(document.querySelectorAll('div')) // 'NodeList'
type(new class XXX {}) // 'XXX'
type(type) // 'Function'