Skip to content
Advertisement

How to access data-state in div id, cheerio node js

I am grateful to everyone who participates and will help a newbie.

Task: Access div = client-state, then div = Here-Goes-Some-Div-ID and return json from data-state.

JavaScript

I managed to refer to div = client state like this –

JavaScript

Unfortunately, I did not find information on how to further access the “Here-Goes-Some-Div-ID” div and get data-state= I would be grateful for the hint, thank you in advance!

Advertisement

Answer

You can go with something like this:

JavaScript

What’s this?

  1. we use the page.$eval method to evaluate a specific DOM element
  2. the first parameter is the CSS selector for the desired element, you can use a descendant combinator – a single space – between the already identified class (.client-state) and the HTML id (#Here-Goes-Some-Div-ID), id-s are using # in front of the id name
  3. the second parameter of the function is the so-called pageFunction where you can do this: el => el.getAttribute('data-state') using Element.getAttribute() on the data-state attribute.

You can define it as a variable and then parse its content with JSON.parse() or whatever you want to do with the result.

Note: in your current example '{"items":[{"action":"LAYOUT"}]' would be unparsable as the wrapper object is not closed with a }!

full example:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement