I am using functions get() and getall() to shorten query selector and query selector all.
const get = (target) => {document.querySelector(target)}
const getAll = (target) => {document.querySelectorAll(target)};
I wanted to fix this code as a function, so I was going to examine the element and create a function get() that return querySelectorAll if there are multiple elements of the same element and return querySelector if not.
So I made the code written below.
const get = (target) => {
if (NodeList.prototype.isPrototypeOf(target)) {
return document.querySelectorAll(target)
} else {
return document.querySelector(target)
}
}
console.log(get('div'));
const get = (target) => {
if(target, target.length > 1) {
return document.querySelectorAll(target);
}else{
return document.querySelector(target)
}
}
const get = (target) => {
if(typeof(target) == 'object') {
return document.querySelectorAll(target);
}else{
return document.querySelector(target)
}
}
However, all of the above codes do not work.
Type of target is string when entering the function.
>Solution :
Simply check the length of the result of document.querySelectorAll.
const get = (target) => {
const els = document.querySelectorAll(target);
return els.length > 1 ? els : els[0];
}