Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

244
Views
¿Cómo devolver un par de valores de un querySelector?

Estoy tratando de obtener un objeto con el valor y el texto interno de un menú desplegable usando un selector de consulta:

 <label> <span>Project :</span> </label> <select name="projectId"> <option value="1">foo</option> <option value="2">bar</option> </select>

Quiero un objeto que se vea así:

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

aquí es de donde vengo

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

pero solo obtengo una cadena del texto interno. No puedo entender cómo lograr mi objetivo, ¿alguien puede ayudarme?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Puede usar document.querySelectorAll para obtener todos los elementos de opción, difundir la sintaxis para convertirlo en una matriz, Array#map para extraer el valor y el texto de cada opción y Object.fromEntries para convertirlo en un solo objeto.

 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>

about 4 years ago · Juan Pablo Isaza Report

0

Si desea obtener varios elementos a través de un selector de consulta, puede usar querySelectorAll . Parece que quieres hacer algo en este sentido:

 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>

about 4 years ago · Juan Pablo Isaza Report

0

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}} }, {}) });
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!