I am getting the error Property 'attribs' does not exist on type 'Element'
while running code. I am not sure why it is throwing this error. I checked the type definitions of cheerio and found that attribs
is the property of TagElement
. I am not sure how can I fix it as it is automatically picking the type Element
for element
. I am new to typescript so maybe I am making a newbie mistake.
const $ = cheerio.load(response.body),
selection = $('td:nth-child(1) .spaceit_pad'),
filteredNodes = [];
selection.toArray().map((element) => {
const attr = element.attribs;
if (attr.class.split(' ').length === 1) {
filteredNodes.push(element);
console.log(typeof element);
}
});
You can try using a typeguard to check if it is a tagElement you found with your selection:
const isTagElement = (element: any): element is cheerio.TagElement => {
return element?.attribs !== undefined;
};
selection.toArray().map((element: cheerio.Element) => {
if (isTagElement(element)) {
const attr = element.attribs;
if (attr.class.split(" ").length === 1) {
filteredNodes.push(element);
console.log(typeof element);
}
}
});