Select elements with an attribute with cheerio

36.9k views Asked by At

What is the most efficient way to select all dom elements that have a certain attribute.

<input name="mode">

With plain javascript I would use : document.querySelectorAll("[name='mode']") or document.querySelectorAll("[name]") if I don't care about the attribute value.

2

There are 2 answers

0
charly rl On BEST ANSWER

Ok I found it in the cheerio documentation, here is how you do it:

$('[name=mode]')

cheerio docs: Selectors

0
Lucio Mollinedo On

For some reason, the accepted answer didn't work for me (using cheerio ^1.0.0-rc.2 here).

But for the following markup:

<input value="123" name="data[text_amount]">

this did work:

$('input[name="data[text_amount]"]'));

The double quote did the magic. Got that from cheerio's help docs.