Пытаюсь так:
let currentIndex = $(".js-practice_button.current").index();
Но значение всегда 0, у какой бы кнопки классcurrent
не присутствовал.
index
по умолчанию определяет индекс элемента среди соседей, а так как у каждой кнопки есть отдельный родитель... Ну да, получаете то, что получаете.const index = $('.js-practice_button.current').closest('li').index();
index
в качестве параметра селектор, то индекс будет определятся не среди соседей, а среди элементов, соответствующих селектору:const index = $('.js-practice_button.current').index('.js-practice_button');
const index = Array.prototype.findIndex.call(
document.querySelectorAll('.js-practice_button'),
n => n.classList.contains('current')
);
// или
const el = document.querySelector('.js-practice_button.current')?.parentNode;
const index = el ? [...el.parentNode.children].indexOf(el) : -1;
// или
let index = -1;
for (
let el = document.querySelector('.js-practice_button.current')?.closest('li');
el;
el = el.previousElementSibling, index++
) ;
const noRepeatingDigits = num => !/(\d).*\1/.test(num);
// или
const noRepeatingDigits = num => -~Math.log10(num) === new Set(`${num}`).size;
// или
const noRepeatingDigits = num => [...'' + num].every((n, i, a) => i === a.indexOf(n));
// или
const noRepeatingDigits = num => String(num)
.split('')
.reduce((acc, n) => (acc[n]++, acc), Array(10).fill(0))
.every(n => n < 2);
// или
const noRepeatingDigits = num =>
!''.match.call(num, /./g).some(function(n) {
return this[n] = Object.hasOwn(this, n);
}, {});
// или
const noRepeatingDigits = num =>
!Array.from(num.toString()).sort().find((n, i, a) => n === a[i + 1]);
arr.splice(0, arr.length, ...arr.filter(noRepeatingDigits));
// или
let numDeleted = 0;
for (let i = 0; i < arr.length; i++) {
const n = arr[i];
arr[i - numDeleted] = n;
numDeleted += !noRepeatingDigits(n);
}
arr.length -= numDeleted;
// или
for (let i = arr.length; i--; ) {
if (!noRepeatingDigits(arr[i])) {
arr.splice(i, 1);
}
}
const newArr = arr.filter(noRepeatingDigits);
// или
const newArr = [];
for (const n of arr) {
if (noRepeatingDigits(n)) {
newArr.push(n);
}
}
// или
const newArr = [];
for (let i = 0; i < arr.length; i++) {
if (noRepeatingDigits(arr[i])) {
newArr[newArr.length] = arr[i];
}
}
// или
const newArr = (function xxx(arr, i = 0) {
return i < arr.length
? (noRepeatingDigits(arr[i]) ? [ arr[i] ] : []).concat(xxx(arr, i + 1))
: [];
})(arr);
const li = Array.prototype.filter.call(
document.querySelector('ul').children,
function(n) {
return this.every(([ k, v ]) => v === n.querySelector(`.${k}`).innerText);
},
Object.entries(items)
);
const li = [];
COLLECT_LI:
for (const n of document.querySelectorAll('li')) {
for (const k in items) {
if (Object.hasOwn(items, k) && items[k] !== n.querySelector('.' + k).textContent) {
continue COLLECT_LI;
}
}
li.push(n);
}
tags = Array.from(new Set(data.flatMap(n => n.tags)));
tags.splice(0, tags.length, ...new Set(data.flatMap(n => n.tags)));
async function getFirstLoadedImage(urls) {
for (const url of urls) {
try {
return await loadImage(url);
} catch (e) {}
}
throw 'ничего загрузить не удалось';
}
getFirstLoadedImage(resolutions.map(n => `https://i.ytimg.com/vi/${videoId}/${n}.jpg`))
.then(img => document.body.append(img))
.catch(console.error);
const getFirstLoadedImage = urls =>
new Promise((resolve, reject) => {
(function next(i) {
if (i === urls.length) {
reject('ничего загрузить не удалось');
} else {
loadImage(urls[i]).then(resolve, () => next(i + 1));
}
})(0);
});
function groupValues(arr, defaultValue = null) {
const keys = [...new Set(arr.flatMap(Object.keys))];
return arr.reduce((acc, n) => {
keys.forEach(k => acc[k].push(Object.hasOwn(n, k) ? n[k] : defaultValue));
return acc;
}, Object.fromEntries(keys.map(k => [ k, [] ])));
}
const result = groupValues(arr);
const groupValues = (arr, defaultValue = null) =>
arr.reduce((acc, n, i, a) => (
Object
.keys(n)
.forEach(k => (acc[k] ??= Array(a.length).fill(defaultValue))[i] = n[k]),
acc
), {});
const classContainer = 'selectboxss';
const classOption = 'selectoption';
const getClasses = el => [...el.classList].filter(n => n !== classOption);
//const getClass = el => el.className.match(RegExp(`${classOption}-\\d+`))[0];
document.addEventListener('click', ({ target: t }) => {
if (t.classList.contains(classOption)) {
const container = t.closest(`.${classContainer}`);
const { classList } = container;
classList.remove(...[...container.querySelectorAll(`.${classOption}`)].flatMap(getClasses));
classList.add(...getClasses(t));
//classList.remove(...Array.from(container.querySelectorAll(`.${classOption}`), getClass));
//classList.add(getClass(t));
}
});
tableValues(element);
element.children
/element.childNodes
.document.querySelector('form').childNodes
children
вместо childNodes
. Ну и погуглите, в чём между ними разница.if (element.nodeType == 1 && element.nodeName == 'INPUT' || element.nodeName == 'SELECT') {
nodeType
лишняя. Кроме того, вам не помешает разобраться с приоритетом выполнения операторов - nodeType
вы тут проверяете только для input'а.let result = [];
const getValues = el =>
el instanceof Element
? [ 'INPUT', 'SELECT' ].includes(el.tagName)
? [ el.value ]
: [...el.children].flatMap(getValues)
: [];
// или
const getValues = el =>
[ 'INPUT', 'SELECT' ].includes(el?.tagName)
? [ el.value ]
: [].flatMap.call(el.children ?? [], getValues);
const values = getValues(document.querySelector('form'));
const values = Array.from(document.querySelector('form').elements, n => n.value);
const getFromDOMNodes = (node, test, getVal) =>
node instanceof Node
? Array.prototype.reduce.call(
node.childNodes,
(acc, n) => (acc.push(...getFromDOMNodes(n, test, getVal)), acc),
test(node) ? [ getVal(node) ] : []
)
: [];
const values = getFromDOMNodes(
document.querySelector('form'),
node => [ 'INPUT', 'SELECT' ].includes(node.nodeName),
node => node.value
);
const values = {
RUS: [ 'раз значение', 'два значение', 'три' ],
US: [ '...', '...', '...' ],
// ...
};
const items = document.querySelectorAll('li');
const buttons = document.querySelectorAll('button');
buttons.forEach(n => n.addEventListener('click', onClick));
function onClick({ target: { innerText: key } }) {
items.forEach(function(n, i) {
n.innerText = this[i] ?? `ЗНАЧЕНИЕ #${i} ДЛЯ ${key} НЕ ЗАДАНО`;
}, values[key] ?? []);
}
const buttonSelector = '.added';
const itemSelector = '.added-block';
const activeClass = '_active';
const notActiveSelector = `${itemSelector}:not(.${activeClass})`;
const newActiveCount = 2;
document.addEventListener('click', e => {
const button = e.target.closest(buttonSelector);
if (button) {
const items = [...button.parentNode.querySelectorAll(notActiveSelector)];
items.slice(0, newActiveCount).forEach(n => n.classList.add(activeClass));
button.disabled = items.length <= newActiveCount;
}
});
str.match(/\d+/g).join('.')
/[^\/]+(?=\/$)/.exec(str)[0]
str.match(/[^\/]+/g).pop()
str.split('/').at(-2)
Хук get не позволяет получить параметры вызова метода
function sequence(functions) {
return new Proxy(functions, {
get(target, key) {
const val = target[key];
return val instanceof Function
? (...args) => {
console.log(`${key} called with arguments: `, args);
return val.apply(target, args);
}
: val;
},
});
}
const groupedArr = arr.reduce((acc, n) => {
const keys = n.slice(0, -1);
let group = acc.find(m => m.length === n.length && keys.every((k, i) => k === m[i]));
if (!group) {
acc.push(group = [ ...keys, 0 ]);
}
group[keys.length] += n[keys.length];
return acc;
}, []);
const groupedArr = arr.reduce((acc, n) => {
const keys = n.slice(0, -1);
const groups = keys.reduce((groups, k) => groups.set(k, groups.get(k) ?? new Map).get(k), acc[1]);
let group = groups.get(acc[2]);
if (!group) {
acc[0].push(group = [ ...keys, 0 ]);
groups.set(acc[2], group);
}
group[keys.length] += n[keys.length];
return acc;
}, [ [], new Map, Symbol() ])[0];
const replaceKeys = (value, replacer) =>
value instanceof Object
? value instanceof Array
? value.map(n => replaceKeys(n, replacer))
: Object.fromEntries(Object
.entries(value)
.map(n => [ replacer(n[0]), replaceKeys(n[1], replacer) ])
)
: value;
const newObj = replaceKeys(obj, k => `${k}_upd`);
function replaceKeys(value, replacer) {
const result = [];
const stack = [];
for (
let i = 0, source = [ [ 0, value ] ], target = result;
i < source.length || stack.length;
i++
) {
if (i === source.length) {
[ i, source, target ] = stack.pop();
} else {
const [ k, v ] = source[i];
const isObject = v instanceof Object;
const newK = target instanceof Array ? k : replacer(k);
target[newK] = isObject ? v.constructor() : v;
if (isObject) {
stack.push([ i, source, target ]);
[ i, source, target ] = [ -1, Object.entries(v), target[newK] ];
}
}
}
return result[0];
}