Search code examples
javascripthtmlgoogle-chrome-extension

How to programmatically select LI from UL using java script in Chrome Extension?


I'm trying to programmatically select an option (LI) from UL from a web site, using a Chrome Extension. The HTML code from the website is as follows;

<ul class="select-options">
<li data-value="0" class="select-items selected">0</li>
<li data-value="1" class="select-items">1</li>
<li data-value="2" class="select-items">2</li>
<li data-value="3" class="select-items">3</li>
<li data-value="4" class="select-items">4</li>
<li data-value="5" class="select-items">5</li>
<li data-value="6" class="select-items">6</li>
<li data-value="7" class="select-items">7</li>
<li data-value="8" class="select-items">8</li>
<li data-value="9" class="select-items">9</li>
</ul>

This is my javascript code in content script;

var xPath = "//ul[( contains(@class,'select-options') )]";
let lst = document.evaluate(xPath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
if (lst != null)
{
    //For example, How to programmatically set the second LI (The item with data-value="1") selected here?
}

Can anyone please point me in right direction to set an specific item selected programmatically, similar to user manually selecting an item from the drop down list?

Any help would be highly appreciated.


Solution

  • It looks got too complex which can be achieved simply. I assume the website does not belongs to you, and just need to automate an user action on the list. If so, try it in the following way.

    function setItem(digit)
    {
        var xPath = "//li[( (@data-value='"+digit+"') )]";
        let lst = document.evaluate(xPath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
        if (lst != null)
        {
            lst.click();
        }    
    }
    

    I used the same XPath way since your sample code uses that way.