
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Set Attribute Value of a WebElement in Selenium
We can set any attribute value of a webelement in Selenium. Selenium can run Javascript commands by the executeScript method. The command to be executed is passed as an argument to the method.
Next, we have to identify the element with the help of the Javascript method document.getElementsByClassname. It returns a list of elements, to point to the first element we shall add index [0]. To set the attribute we shall use the setAttribute method.
Syntax for setting the style attribute −
JavascriptExecutor j = (JavascriptExecutor) driver; js.executeScript ("document.getElementsByClassName('heading')[0].setAttribute('style', 'background-color: red')");
Let us set the background color of webelement to red.
Example
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.JavascriptExecutor; public class SetAttributeVal{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://www.tutorialspoint.com/index.htm"); // Javascript executor to set background color to red JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript js.executeScript ("document.getElementsByClassName('heading')[0].setAttribute('style', 'background-color: red')"); driver.quit(); } }
Output
Advertisements