Automated testing and dynamic ID’s


First off, if you’ve never used the testing tools Selenium or WebTest, you should give them a try.  Each of these tools is used to generate and run scripted interaction with your Web site (i.e. Web app functional testing).

As I built a regression test for a bug I found, I needed to automate selecting an option from a drop-down. Usually the test recorders handle this for me, and I give it no thought.  The catch is, the ‘id’ of the select element could be different on any given test run.  What I really needed was to choose a select element based on its label rather than its ‘id.’

Consider this (dynamically generated) HTML fragment:

<label for="arbitraryElementId">Product</label>
<select name="productX_another_arbitrary_id" id="arbitraryElementId">

<label for="somethingElse">Qty</label>
<select name="qtyX_another_arbitrary_id" id="somethingElse">

How can I locate the correct select element without referencing them by ID?


That would work great if I knew the ID ahead of time.  That’s where the ‘for’ attribute comes in handy:


That will get me the for attribute of the “Product” label.  Putting it all together, it looks like this:


Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: