Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium get class attribute of element with javascript

I am using using Selenium to write test automation with Javascript. Trying to extract class attributes of a DOM element does not work for me. Here is my code:

var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().
            withCapabilities(webdriver.Capabilities.ie()).
            build();
var usernameField = driver.findElement(webdriver.By.id('username'));
var classes = usernameField.getAttribute('class');
console.log(classes);

This prints the following:

{ then: [Function: then],
cancel: [Function: cancel],
isPending: [Function: isPending] }

Please indicate how to find the attribute values of the element.

like image 496
Lilit Yenokyan Avatar asked Jan 22 '14 20:01

Lilit Yenokyan


People also ask

How do you fetch an attribute value of an element in Selenium?

The getAttribute() method fetches the text contained by an attribute in an HTML document. It returns the value of the HTML element's attribute as a string. If a value is not set for an attribute, it will return a NULL value. For attributes with Boolean values, getAttribute() will return either "True" or NULL.

How do I find the class of an element in Selenium?

We can find an element using the attribute class name with Selenium webdriver using the locators - class name, css, or xpath. To identify the element with css, the expression should be tagname[class='value'] and the method to be used is By. cssSelector.

How do you find the element for the tag class and attribute?

Type “css=input[type='submit']” (locator value) in Selenium IDE. Click on the Find Button. The “Sign in” button will be highlighted, verifying the locator value. Attribute: Used to create the CSS Selector.

How do I get css properties of a WebElement?

We can get the css class name of an element with Selenium webdriver. To obtain the class name attribute of an element in the html document, we have to use the getAttribute() method. Then the class value is passed as a parameter to the method.


1 Answers

Found the issue, console.log() was being fired asynchronously before any values were assigned. Forcing it to execute sequentially using then statement fixed the problem.

var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().
        withCapabilities(webdriver.Capabilities.ie()).
        build();
var usernameField = driver.findElement(webdriver.By.id('username'));
usernameField.getAttribute('class')
.then(function(classes){
    console.log(classes);
 });
like image 131
Lilit Yenokyan Avatar answered Sep 28 '22 19:09

Lilit Yenokyan