Home > database >  how to return a couple of value from a querySelector?
how to return a couple of value from a querySelector?

Time:11-02

I'm trying to get an object with the value and the inner text from a dropDown menu using a query selector:

<label>
  <span>Project :</span>
</label>
<select name="projectId">
  <option value="1">foo</option>
  <option value="2">bar</option>
</select>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

I want an object that look like this:

{
    "1":"foo",
    "2":"bar"
}

here's where I come from

let options = await page.evaluate(() => {
                return document.querySelector('select[name=projectId]').innerText;
            });

but I only get a string of the inner text I can't figure out how to achieve my goal, can anyone help ?

CodePudding user response:

You can use document.querySelectorAll to get all the option elements, spread syntax to convert it to an array, Array#map to extract the value and text of each option, and Object.fromEntries to convert it to a single object.

const res = Object.fromEntries(
  [...document.querySelectorAll("select[name=projectId] > option")]
    .map(o => [o.value, o.text]));
console.log(res);
<label>
  <span>Project :</span>
</label>
<select name="projectId">
  <option value="1">foo</option>
  <option value="2">bar</option>
</select>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

let options = await page.evaluate(() => {

  // Get all option items
  const options =  Array.from(document.querySelectorAll('select[name=projectId] option'));
  // Iterate through all option items and set corresponding object properties
  return options.reduce((acc, item) => {
    return {...acc, ...{[item.value]: item.innerText}}
  }, {})

});

CodePudding user response:

If you want to get multiple elements via a query selector, you can use querySelectorAll. It looks like you want to do something along these lines:

const options = document.querySelectorAll('[name="projectId"] option');

const optionData = {};
for (let option of options) {
  optionData[option.value] = option.innerText;
}

console.log(optionData);
<label>
  <span>Project :</span>
</label>
<select name="projectId">
  <option value="1">foo</option>
  <option value="2">bar</option>
</select>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

simply ?

console.log( 
  Object.fromEntries(
  Array.from(
    document.querySelector('select[name=projectId]').options
    ,el=>[el.value,el.textContent] 
) ) )
<select name="projectId">
  <option value="1">foo</option>
  <option value="2">bar</option>
</select>
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related