How to get Dynamic ID from an element

1,807 views
Skip to first unread message

Mahmudul Hasan

unread,
Aug 20, 2015, 8:22:47 AM8/20/15
to NightwatchJs
I am writing scripts to select an element using its id but the id is generated dynamically. How to do it?

Corrinna Rainwater

unread,
Aug 20, 2015, 6:32:40 PM8/20/15
to NightwatchJs
You don't have to select the element by ID, any css selector will work too. In the dev tools in Chrome for example you can right click on an element and copy the css selector. Xpath works too but you need to specify that you use an xpath in nightwatch.
Here an example for a css selector browser.click('#oneup-header > div.controls > ul') and here for an xpath browser.useXpath().click('//*[@id="oneup-header"]/div[2]/ul')

Hope this helps.

Mahmudul Hasan

unread,
Aug 23, 2015, 4:38:18 AM8/23/15
to NightwatchJs
I do not want to use xpath as xpath is not bad in terms of test management. Is there any way I can get the attribute is and use it as selector?

Ellen Wong

unread,
Aug 24, 2015, 12:42:40 PM8/24/15
to NightwatchJs
If the dynamic ID follows some particular pattern you can select it using attribute selectors. https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors 

For example:

<div id="dynamic12afadsf34"> .... </div>

You can select this with 'div[id^=dynamic]' which is select the div that has an attribute id that begins with dynamic

You might also be able to select the element by selecting its parent and using > to get its direct children. This is the same as Corrinna's response above: '#oneup-header > div.controls > ul'

You might even need to use a combination of these two methods. If you post the source that you're working with, we can offer some more guidance. 

Corrinna Rainwater

unread,
Aug 24, 2015, 6:53:58 PM8/24/15
to NightwatchJs
Yes, exactly what Ellen said. You can check for any attribute, not just class or ID. Could also be for example a data attribute.

Mahmudul Hasan

unread,
Aug 25, 2015, 12:53:35 AM8/25/15
to NightwatchJs
Hi Ellen,

Thanks for the Help I can access dynamic elements using your help. 

Ketan Patel

unread,
Dec 27, 2017, 10:30:37 AM12/27/17
to NightwatchJs
Hi Ellen,

I am trying to click on the Card number field and the id for this is generated Dynamically. Please help attached is a snapshot

Reply all
Reply to author
Forward
0 new messages