MJJ_PDX
MJJ_PDX

Reputation: 13

How to find element with non-static ID using Selenium Webdriver C#

I want to be able to send text to this text box element:

<form class="compose okform initialized">

    <div class="border"></div>
    <div id="message_9028519832635440005Container" class="inputcontainer textarea empty">
        <textarea class="clone" placeholder="Compose your message" aria-hidden="true" style="height: 21px; width: 417px; line-height: 18px; text-decoration: none; letter-spacing: 0px;" tabindex="-1"></textarea>
        <textarea id="message_9028519832635440005" placeholder="Compose your message" style="height: 39px;"></textarea>

        <span class="okform-feedback message empty" style="height: 0"></span>
        <div class="icon okicon"></div>
    </div>
    <button class="flatbutton" type="submit"></button>
    <div class="draft_message"></div>
    <label class="checkbox" for="enter_to_send_9028519832635440005"></label>

</form>

I'm not able to location the element by searching for part of the ID (the number after message_ is dynamically generated).

I've also tried this but I get an error saying "unknown error: cannot focus element":

var textBox = DriverActions.driver.FindElements(By.ClassName("inputcontainer"));
textBox[0].SendKeys("Why hello");

Upvotes: 1

Views: 3215

Answers (2)

bit
bit

Reputation: 4487

Try this XPath using starts-with

var textBox= DriverActions.driver.FindElement(By.XPath(".//textarea[starts-with(@id,'message_')]"));
textBox.SendKeys("Why hello");

The reason that you are getting the error could be because by your selector you will end up getting a div instead of a textBox that you need.

Upvotes: 0

Saifur
Saifur

Reputation: 16201

Try the following css

.inputcontainer.textarea.empty>textarea:nth-child(1)

I assumed you want the first text area box with placeholder="Compose your message" if so, you can also use the following cssSelector

[placeholder='Compose your message'][class='clone']

Partial search with id is also possible. Assuming the Container part of the div's id is unique and static, you can do the following

[id$='Container']>textarea:nth-child(1)

On the other hand, if you want the second textarea just simply change the child index

[id$='Container']>textarea:nth-child(2)

And, here is the implementation

By byCss = By.CssSelector("[id$='Container']>textarea:nth-child(1)");
IWebElement textBox = driver.FindElement(byCss);
textBox.SendKeys("Why hello");

Upvotes: 1

Related Questions