admin管理员组

文章数量:1201570

I am using Selenium WebDriver and Protractor to run e2e tests on my angular project. Let's say I have an element like:

<div my-directive my-unique-id="abc123"></div>

How can locate the above element. I tried with element(by.css('div[my-unique-id="abc123"]'));, but it gives a NoSuchElementError.

If I try with HTML attributes like, for example, I want to locate:

<a title="myTitle" href="">Click me</a>

I was able to locate the element correctly using element(by.css('a[title="myTitle"]'))

How do I locate the element with custom attributes, if it does not have any standard HTML attributes?

I am using Selenium WebDriver and Protractor to run e2e tests on my angular project. Let's say I have an element like:

<div my-directive my-unique-id="abc123"></div>

How can locate the above element. I tried with element(by.css('div[my-unique-id="abc123"]'));, but it gives a NoSuchElementError.

If I try with HTML attributes like, for example, I want to locate:

<a title="myTitle" href="">Click me</a>

I was able to locate the element correctly using element(by.css('a[title="myTitle"]'))

How do I locate the element with custom attributes, if it does not have any standard HTML attributes?

Share Improve this question edited May 13, 2014 at 11:17 Madhura Adawadkar asked May 13, 2014 at 11:10 Madhura AdawadkarMadhura Adawadkar 1921 gold badge2 silver badges11 bronze badges 2
  • The syntax is correct. Does you directive render as a div with an attribute my-unique-id="abc123"? Check the element that is rendered in the browser using the developer tools and test it with $('your-css-selector'). It should work the same way in protractor. – Andres D Commented May 15, 2014 at 0:50
  • Agree with @AndresD, the most likely cause for this is that your directive replaces the current element it's defined on with its own template. Check the element in devtools to make sure you have the right CSS selector. – Morgan Polotan Commented Mar 4, 2015 at 19:13
Add a comment  | 

2 Answers 2

Reset to default 18

Try to use xpath:

element(by.xpath('//div[@my-unique-id="abc123"]'))

or only by attribute

element(by.xpath('//div[@my-unique-id]'))

try using:

element(by.css('[my-unique-id="abc123"]'))

it's easier and more readable than xpath for simple cases.

more about xpath syntax and when it is usefull: http://www.w3schools.com/xml/xml_xpath.asp

本文标签: javascriptProtractorHow to locate element by custom (non HTML) attributesStack Overflow