Explore Courses Blog Tutorials Interview Questions
0 votes
in DevOps and Agile by (19.7k points)

I'm trying to get the currently selected text in input using window.getSelection() but I'm always getting an empty string:

expect(browser.executeScript("return window.getSelection().toString();")).toEqual("test");

Results into:

Expected '' to equal 'test'.

The complete reproducible test using as a target site:

describe("My test", function () {

    beforeEach(function () {



    it("should select text in an input", function () {

        var query = element(by.css(""));


        query.sendKeys(protractor.Key.chord(protractor.Key.COMMAND, "a"));

        expect(browser.executeScript("return window.getSelection().toString();")).toEqual("test");



Note that I actually see the entered text being selected with COMMAND + "a".

What am I doing wrong?

Using protractor 2.5.1, firefox 41.

1 Answer

0 votes
by (62.9k points)

You can use the jQuery :selected selector in combination with the val() method to find the selected option value in a select box or dropdown list.

If the value for an option is not defined specifically, the text content of the <option> element will be used as a value instead, as shown in the following code:


<!DOCTYPE html>

<html lang="en">


<meta charset="UTF-8">

<title>jQuery Get Selected Option Text</title>

<script src=""></script>

<script type="text/javascript">



        var selectedCountry = $(this).children("option:selected").val();

        alert("You have selected the country - " + selectedCountry);







        <label>Select Country:</label>

        <select class="country">

            <option>United States</option>


            <option>United Kingdom</option>





Alternatively, you can use the jQuery text() method to get the text content of an element.

Browse Categories