nightmare

How do I select both innerText and value from an Option tag using NightmareJS 3.0.1


I was working through something and saw that I could easily concatenate the two returned arrays but it's not very DRY.... How would you have approached doing this???? I'm in need of the option text AND the value as they're different things but need them returned into the same object so that I can do work with said values returned...preferrably if I could somehow map-reduce it so the function returns a key/value object that would be even better but I'm not sure that's possible:

//define a new Nightmare method named "textExtract"
//note that it takes a selector as a parameter
Nightmare.action('textExtract', function(selector, done) {
    //`this` is the Nightmare instance
    this.evaluate_now((selector) => {
      //query the document for all elements that match `selector`
      //note that `document.querySelectorAll` returns a DOM list, not an array
      //as such, convert the result to an Array with `Array.from`
      //return the array result
      text =  Array.from(document.querySelectorAll(selector))
        //extract and return the text for each element matched
        .map((element) => element.text );
      elValues =  Array.from(document.querySelectorAll(selector))
        //extract and return the text for each element matched
        .map((element) => element.value );
        return text.concat(elValues)
    //pass done as the first argument, other arguments following
    }, done, selector)
  });

referenced from github.


Solution

  • How about this:

    Nightmare.action('textExtract', function(selector, done) {
      this.evaluate_now((selector) => {
        return Array.from(document.querySelectorAll(selector))
          .map(o => ({value: o.value, text: o.text}))
      }, done, selector)
    })
    

    results in something like:

    [
      { text: 'Bob', value: '766' },
      { text: 'Renee', value: '768' },
      { text: 'Paul', value: '787' }
    ]