Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fastest possible way to see if an element exists #1265

Closed
peterbe opened this issue Jan 1, 2019 · 2 comments
Closed

Fastest possible way to see if an element exists #1265

peterbe opened this issue Jan 1, 2019 · 2 comments

Comments

@peterbe
Copy link

peterbe commented Jan 1, 2019

I'm sorry if this isn't a feature request or bug but I'm hunting for a way to use cheerio in the fastest possible way and my use case is simple. I just want to find out if an element exists. I don't need the element or know how many there are.

What I'm currently doing is something like this:

const $ = cheerio.load(htmlString)
cssselectors.forEach(selector => {
  if ($(selector).length) {
    console.log('It exists!')
  } else {
    console.log('Does not exist')
  }
}

In my use case I have hundreds or thousands of CSS selectors and I just want to find out, for each one, if there exists an element at all.

@fb55
Copy link
Member

fb55 commented Dec 22, 2020

First thing that comes to mind is to use css-select directly (cheerio uses css-select as its selector engine). Something like this:

const {selectOne} = require('css-select')

const $ = cheerio.load('<document>')
const doesElementExist = !!selectOne('.someSelector', $.root().get(), $._options)

This way, each search terminates as soon as an element was found.

@fb55 fb55 closed this as completed Dec 22, 2020
@fb55
Copy link
Member

fb55 commented Jan 14, 2021

Another option would be to use

$.root().filter(`:scope:has(${mySelector})`)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

2 participants