I am using javascrypt with selenium. I need to search and select one of the items in this list, but I am unable to select it. I can find it, but not select the element. Please help me, thank you very much
var input = document.evaluate("//li[contains(., 'ATACAMA')]", document, null, XPathResult.ANY_TYPE, null );
var thisregion = input.iterateNext();
thisregion.click();
CodePudding user response:
You could try the following below:
var input = document.evaluate("//li[text()='ATACAMA']", document, null, XPathResult.ANY_TYPE, null );
var thisregion = input.iterateNext();
thisregion.click();
CodePudding user response:
So I don't have a clue about Xpath, but like you said, there is nothing stopping you from using querySelector
or in this case querySelectorAll
instead.
Here I create an array of all the li
elements and use .find
to get the element that has the text "Item 3" in it. I then click the element programmatically. All of the li
elements have onClick
event inline in the html.
Would this work for you?
let li_item = Array.from(document.querySelectorAll('li'))
.find(x => x.textContent === 'Item 3');
li_item.click();
function select(element, n) {
element.style.color = "red";
console.log(`${n} has been selected!`);
}
<ul>
<li onClick = "select(this, 1)">Item 1</li>
<li onClick = "select(this, 2)">Item 2</li>
<li onClick = "select(this, 3)">Item 3</li>
<li onClick = "select(this, 4)">Item 4</li>
<li onClick = "select(this, 5)">Item 5</li>
</ul>