I am looking to create a custom find selector instead of relying on standard javascript querySelector tags. To achieve this, I have extended the Element type with my own function called addClass(). However, I encountered an issue where querySelectorAll returns a NodeListof Element while querySelector returns just a single Element. This inconsistency led TypeScript to flag an error since the result of find could be either a NodeListof Element or just a single Element. My goal is to be able to utilize my find function for both single and multiple element selections, and also apply my custom functions like addClass or forEach (which are NodeList methods).
function find(selector: string)
{
let elements = document.body.querySelectorAll(selector);
if (elements.length === 1) return elements[0] as Element;
else return elements;
}
interface Element
{
addClass(className: string): Element;
}
Element.prototype.addClass = function (className)
{
this.classList.add(className);
return this;
}
In order to address this issue, I attempted to add a forEach method to the Element interface and extend the NodeList interface with my custom Element interface. However, I suspect that this may not adhere to best practices in TypeScript. Despite this, I was able to successfully implement forEach for a single Element and addClass method for a NodeList Element.
interface Element
{
addClass(className: string): Element;
forEach(callback: Function): any;
}
interface NodeList extends Element {}
Element.prototype.forEach = function (myFunction: Function)
{
myFunction(this);
}
Additionally, I introduced a find method within my Element interface
interface Element
{
addClass(className: string): Element;
forEach(callback: Function): any;
find(selector: string): NodeList | Element;
}
Element.prototype.find = function (selector)
{
let elements = document.body.querySelectorAll(selector);
if (elements.length === 1) return elements[0] as Element;
else return elements;
}
While this solution works for now, I am curious if there is a more efficient approach to resolving this problem in TypeScript?