Search code examples
puppeteersemantic-uisemantic-ui-react

puppeteer semantic-ui-react dropdown how to select options


    <div role="listbox" aria-disabled="false" aria-expanded="false" class="ui selection dropdown content--content-type:-selector" tabindex="0" style="width: 100%;"><div class="default text" role="alert" aria-live="polite" aria-atomic="true">Select type</div><i aria-hidden="true" class="dropdown icon"></i><div class="menu transition"><div role="option" aria-checked="false" aria-selected="true" class="selected item" style=`enter code here`"pointer-events: all;"><span class="text">Single</span></div><div role="option" aria-checked="false" aria-selected="false" class="item" style="pointer-events: all;"><span class="text">Multi</span></div><div role="option" aria-checked="false" aria-selected="false" class="item" style="pointer-events: all;"></div></div></div>

Very beginner in puppeteer. I am looking to select dropdown options.


Solution

  • If there is no unique selector for the dropdown element - so you could grab it - then you can use an XPath with contains(text(), {string}), do the search inside the container tag, in this case it is the <span>. After we've grabbed the item a simple click will emulates that a real user selects the element.

    (In the last three lines I've put a validation just to see if we've successfully selected the dropdown option.)

    Let's see it in case of "Single" option:

      const optionSingle = await page.$x('//span[contains(text(), "Single")]')
      await optionSingle[0].click()
    
      // if we did everything correctly the `'.selected, .item'` classes will be applied on the selected item
      const selectedItemInnerText = await page.evaluate(el => el.innerText, (await page.$$('.selected, .item'))[0])
      selectedItemInnerText === 'Single' ? console.log('We\'ve succesfully selected the item :)') : console.log('Something went wrong :(')
    

    Note: You may need to click inside the listbox first. Obviously I don't see the CSS of your example so I cannot tell if this specific case requires it or the options can be selected without it.

    Suggestion: Test out the XPath (or selector) in Chrome DevTools like this: $x('//span[contains(text(), "Single")]')[0].click(). If it does select the desired option: it will work in puppeteer as well.