Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select elements with an attribute with cheerio

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.

like image 722
charly rl Avatar asked Dec 16 '16 23:12

charly rl


People also ask

How do you select an element with an attribute?

The [attribute|="value"] selector is used to select elements with the specified attribute, whose value can be exactly the specified value, or the specified value followed by a hyphen (-). Note: The value has to be a whole word, either alone, like class="top", or followed by a hyphen( - ), like class="top-text".

How do you get attribute value in Cheerio?

Cheerio get element attributesAttributes can be retrieved with attr function. import fetch from 'node-fetch'; import { load } from 'cheerio'; const url = 'http://webcode.me'; const response = await fetch(url); const body = await response. text(); let $ = load(body); let lnEl = $('link'); let attrs = lnEl.

How does Cheerio work?

Cheerio parses markup and provides an API for traversing/manipulating the resulting data structure. It does not interpret the result as a web browser does. Specifically, it does not produce a visual rendering, apply CSS, load external resources, or execute JavaScript which is common for a SPA (single page application).


2 Answers

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

$('[name=mode]')

cheerio docs: Selectors

like image 159
charly rl Avatar answered Oct 19 '22 20:10

charly rl


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.

like image 11
Lucio Mollinedo Avatar answered Oct 19 '22 18:10

Lucio Mollinedo