3
votes

How can text of a web element be set using java script executor? Or is there any other way to do this?

<a class="selectBox selectBox-dropdown selectBox-menuShowing selectBox-active" style="width: 52px; display: inline-block; -moz-user-select: none;" title="" tabindex="0">
<span class="selectBox-label" style="width: 13px;">10</span>
<span class="selectBox-arrow"/>
</a>

There are two span elements under the tag - which is a drop down. User clicks on span[2] and a list is shown which contains data like 10, 20, 30, 40, etc.. User clicks on the number(element) and that is set as the text of span[1] (In this case, 10 is selected). How should I go about solving this?

I tried Action builder and it is not working. Any others suggestions?

1
Don't understand your question. What do you want to do? You can set text on clicking the 2nd span right? So why don't you do that, I mean click on the number element?? - Husam
@Husam: User clicks on span[2] which is just an arrow button. a list is displayed after this click. User clicks on one of the elements in the list. The text in clicked element is set as the text of span[1]. I tried doing this with action builder - No luck! any other suggestions. - Mike
Provide html of the list. If the Actions class really did not work. You may try to - Use java script to click on the number, java script would not need the element to be displayed for being clicked.. - Husam
Action class did not work! Using java script I can change an attribute of the element, but how do I change the text of the element ? <span class="selectBox-label" style="width: 13px;">10</span> In this case, I want to change the 10 to 2000. - Mike

1 Answers

5
votes

If you want to change the text of span[1] directly, you may use following code:

String jScript = "var myList = document.getElementsByClassName(\"selectBox-label\");"
    +"myList[0].innerHTML=\"YourNumber\";"; 
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript(jScript);

However, you may also click the number using java script which as you say will set the text of span[1]. Example below:

WebElement element = driver.findElement(By.xpath("YourNumbersXpath"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);