tbone
tbone

Reputation: 882

Ruby Watir, how to change the class of a DOM element?

In Watir, how would I change the class of a DOM element? Actually I need to remove one of the classes of the element (of three)?

I've tried a number of possible solutions but can't get any of them to work. Anything would be helpful.

Upvotes: 1

Views: 1233

Answers (1)

Justin Ko
Justin Ko

Reputation: 46846

As a regular user would not directly change an element's class, Watir has not provided a method for directly doing this. However, since removing a class is possible with Javascript, you can do this through the execute_script method.

Say we have a page with some text that has three classes - one to make the text large, one to make the text red and one to make the text bold:

<html>
  <head>
    <style>
      .label {font-size: 14em;}
      .required {font-weight: bold;}
      .error {color: red;}
    </style>
  </head>
  <body>
    <span class="label required error">text</span>
  </body>
</html>

We can remove one of the classes, say the class that makes the text red, by executing Javascript against the page:

# Locate the element in Watir
element = browser.span

# Check that the text's original color is red
p element.style('color')
#=> "rgba(255, 0, 0, 1)" (red)

# Execute Javascript to remove the required class, which makes the text red
browser.execute_script('arguments[0].classList.remove("error");', element)

# Check that the text's new colour is now black
p element.style('color')
#=> "rgba(0, 0, 0, 1)" (black)

The classList method is only supported in certain browser versions. I believe Chrome/Firefox have supported it for quite a while, where as IE needs at least version 10. If you need to support older browsers, you could also do a string replacement:

browser.execute_script('arguments[0].className = arguments[0].className.replace( /(?:^|\s)error(?!\S)/ , "" )', element)

You could also use JQuery if you have it available.

Note that in the execute_script, we use Watir/Selenium's special arguments array so that we can pass Watir elements to the Javascript. I find that this is easier for locating elements, but you can also locate the element using Javascript if you prefer.

Upvotes: 2

Related Questions