Как получить не `NodeList []`, а `null` при вызове функции querySelectorAll?
Я использовал код из ответа https://stackoverflow.com/a/63586304/12143273
window.$ = HTMLElement.prototype.$ = function(selector) {
if (this === window) {
return document.querySelector(selector);
} else {
return this.querySelector(selector);
}
};
Если я пытаюсь найти несуществующий элемент, то получаю null.
Теперь я изменил вызов функции querySelector на querySelectorAll
window.$ = HTMLElement.prototype.$ = function(selector) {
if (this === window) {
return document.querySelectorAll(selector);
} else {
return this.querySelectorAll(selector);
}
};
Если я пытаюсь найти несуществующий элемент, то получаю NodeList [].
Как мне нужно более корректно использовать функцию querySelectorAll или как-то переписать функцию $ чтобы она возвращала не NodeList [], а null при поиске несуществующего элемента?
Ответы (2 шт):
querySelectorAll всегда будет возвращать non-null пустой список.
Return Value: A non-live NodeList containing one Element object for each element that matches at least one of the specified selectors or an empty NodeList in case of no matches.
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll#return_value
Однако вы можете просто обработать этот случай:
window.$ = HTMLElement.prototype.$ = function(selector) {
var list;
if (this === window) {
list = document.querySelectorAll(selector);
} else {
list = this.querySelectorAll(selector);
}
if(list.length == 0){
return null;
} else {
return list;
}
};
Только через дополнительную проверку длины вернувшегося NodeList:
window.$ = HTMLElement.prototype.$ = function(selector) {
const nodes = ((this === window) ? document : this).querySelectorAll(selector);
return nodes.length ? nodes : null;
}