Execute a selector on child elements using cheerio

I am struggling to apply selectors to elements in cheerio (version 1.0.0-rc.3). Attempting to use find() results in an error.

const xmlText = `
<table>
  <tr><td>Foo</td><td/></tr>
  <tr><td>1,2,3</td><td>number</td></tr>
  <tr><td>A,B</td><td>char</td></tr>
  <!-- more rows -->
</table>
<table>
  <tr><td>Bar</td><td/></tr>
  <!-- more rows -->
</table>
`
const $ = cheerio.load(xmlText)
$('table').each((i, table) => {
  // TODO if first row contains Foo then map the following rows
  if (table.find("td:contains('Foo')").length > 0) {
    // ...
  }
})

'CheerioElement' does not have a property 'find'.

How can I access sub elements using selectors?

I want the example given to only process tables with the text 'Foo' in the first row and return a list of objects as shown below.

// desired result
[{ value: '1,2,3', type: 'numbner' }, { value: 'A,B', type: 'char' }, ...]

Answer №1

Starting fresh, there has to be a more efficient approach:

$('table').each((index, element) => { if ($(element).find("td:contains('Foo')").length > 0) {$('tr', element).each((ind, row)=>{console.log($(row).text())})} })

Answer №2

I came across the solution by going through the each() method's documentation. To make it work, you need to enclose the provided element with $(element).

if ($(table).find("td:contains('Foo')").length > 0) {

After implementing this fix, I was able to resolve the issue.

const $ = cheerio.load(xmlText)
const isFooTable = (i: number, e: CheerioElement) =>
  $('td', e).first().text() === 'Foo'
const result: { value: string; type: string }[] = []

$('table')
  .filter(isFooTable)
  .find('tr')
  .slice(1)
  .each((_, tr) => {
    const tds = $(tr).find('td')
    result.push({
      value: tds.first().text(),
      type: tds.last().text(),
    })
  })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is the Prisma model not reachable through Prisma Client?

I'm currently attempting to retrieve a specific property of a Prisma model using Prisma Client. The model in question is related to restaurants and includes a reviews property that also corresponds with a separate Review model. schema.prisma file: // ...

Aurelia: The passing down of views and view-models

In the process of developing an Aurelia app, I am tasked with creating functionality that allows users to display various lists for different resources. These lists share common features such as a toolbar with search and refresh capabilities, along with a ...

Unsure how to proceed with resolving lint errors that are causing changes in the code

Updated. I made changes to the code but I am still encountering the following error: Error Type 'String' is not assignable to type 'string'. 'string' is a primitive, but 'String' is a wrapper object. It is recom ...

Resolving type error issues related to using refs in a React hook

I have implemented a custom hook called useFadeIn import { useRef, useEffect } from 'react'; export const useFadeIn = (delay = 0) => { const elementRef = useRef<HTMLElement>(null); useEffect(() => { if (!elementRef.current) ...

Utilizing Logical Operators in Typescript Typing

What is the preferred method for boolean comparisons in Typescript types? I have devised the following types for this purpose, but I am curious if there is a more standard or efficient approach: type And<T1 extends boolean, T2 extends boolean> = T1 ...

Tips for sorting an array of objects by multiple keys while maintaining the order of each key that comes before

I am looking to create a versatile function that can organize an array of objects based on specified keys, while maintaining the order of previous keys. Here is a sample scenario: const input = [ { a: 'aardvark', b: 'bear', c: 'c ...

Discovering the process of reaching service members through an HTML View

Currently, I am in the process of learning Angular 2 and find myself unsure about the most efficient way to update the view. For instance, let's say I have two components: User and Main. The User component retrieves a list of users from the UserServ ...

Deploying AWS CDK in a CodePipeline and CodeBuild workflow

I am currently attempting to deploy an AWS CDK application on AWS CodePipeline using CodeBuild actions. While the build and deploy processes run smoothly locally (as expected), encountering an issue when running on CodeBuild where the cdk command fails w ...

Exploring React State Management: Leveraging the Context API as a centralized store for

Currently, I am developing a React web application using TypeScript. To enhance the State Management, I decided to implement React Hooks and Context API by following a concise tutorial that I came across here. Despite diligently following the tutorial, my ...

Strange occurrences with HTML image tags

I am facing an issue with my React project where I am using icons inside img tags. The icons appear too big, so I tried adjusting their width, but this is affecting the width of other elements as well. Here are some screenshots to illustrate: The icon wit ...

Insight on the process of submitting interactive forms

I'm facing a challenge that I can't seem to figure out It's a form structured in HTML like this: <button (click)="addform()">add form</button> <div class="conten-form"> <div class="MyForm" ...

Combine the AnimatedMarker from leafletjs with typescript

After installing leaflet typescript, I encountered issues when trying to use leaflet non-typescript plugins. For instance, I had no problem importing the leaflet-routing-machine plugin by following these steps: installation: npm install --save leaflet-ro ...

`How to Merge Angular Route Parameters?`

In the Angular Material Docs application, path parameters are combined in the following manner: // Combine params from all of the path into a single object. this.params = combineLatest( this._route.pathFromRoot.map(route => route.params) ...

Modify the empty message for the PrimeNG multiselect component

Is there a way to customize the message 'no results found' in p-multiselect on Angular? I have successfully changed the default label, but I am struggling to find a solution to override the empty message. Here is my code snippet: <p-multiSel ...

Minimize the amount of information retrieved and shown based on the timestamp

I am currently working on storing and retrieving the date of a user request. For creating the timestamp, I use this code: const date = firebase.firestore.FieldValue.serverTimestamp(); This is how I fetch and display the data: <tr class="tr-content" ...

I am not currently working on developing an angular application

Seeking assistance for the issue described below, as I have been struggling with it for three days. Any help would be greatly appreciated. Despite multiple attempts, the situation only seems to worsen with each try. The problem arises when attempting to ...

Transferring information to a deep-level interface

I am currently working on creating an object that aligns with my interface structure. Success Story export interface ServiceDataToDialog { id: number, service: string, } constructor(private _dialogRef: MatDialogRef<DialogServiceTabletAddRowComp ...

What could be causing my TypeScript code to not be recognized as CommonJS?

I rely on a dependency that is transpiled to ES6. My goal is to leverage ES2019 features in my own code. Ultimately, I aim to output ES6. This is how I set up my tsconfig { "compilerOptions": { "module": "CommonJS" ...

What steps can be taken to resolve the TS5023 error that arises when including "allowImportingTsExtensions" in the tsconfig.json file?

While working on my React project, I've encountered a specific error that reads: Could not parse tsconfig.json. Please ensure it contains valid JSON syntax. Details: error TS5023: Unknown compiler option 'allowImportingTsExtensions'. I tr ...

Error: Unable to convert null or undefined to an object | NextAuth

Recently, I've been attempting to implement a SignIn feature with Nextauth using the following code: import { getProviders, signIn as SignIntoProvider} from "next-auth/react"; function signIn({ providers }) { return ( <> ...