javascriptjestjsjsdom

Get the Value of HTML Element Using JSDom


Seems like this should be really fundamental action, yet I can't find any documentation or examples on how to do this. If I have some HTML, and I want to retrieve a particular value and set it as a variable, how do I do that?

Context: Working with an old MVC single layer app that only returns HTML responses.

Example:

const { JSDOM } = require('jsdom');

const kmsiResponse = await post(
      {
        ctx: loginCtx,
        hpgRequestId: loginSessionId,
        flowToken: loginSft,
        canary: loginCanary,
      },
      { url: 'myUrl' }
    );

    const kmsiResponseText = await kmsiResponse.text();
    const kmsiDom = new JSDOM(kmsiResponseText);
    console.log('JSDOM', kmsiDom.window.document.getElementsByName('id_token'));
<form method="POST" name="hiddenform" action="https://someUrl/">
   <input type="hidden" name="id_token" value="xxxxxxxxxx">
</form>

Output: JSDOM NodeList {}


Solution

  • Based on @Scott Marcus comment, this works:

    console.log('JSDOM', kmsiDom.window.document.querySelector("[name = 'id_token']").value);
    

    Console output - JSDOM xxxxxxx

    I do need to also retrieve a list of values for another request, so will also be referencing the comments related to iteration, thanks all!