jimwan
jimwan

Reputation: 1136

How to modify css by class name in selenium

I am learning how to use Selenium in python and I try to modify a css style on http://www.google.com. For example, the <span class="gbts"> ....</span> on that page. I would like to modify the gbts class.

browser.execute_script("q = document.getElementById('gbts');" + "q.style.border = '1px solid red';")

Is there an API method called getElementByClass('gbts') ?

Upvotes: 5

Views: 10111

Answers (2)

Mark Salvin
Mark Salvin

Reputation: 21

Another pure JavaScript option which you may find gives you more flexibility is to use document.querySelector().

Not only will it automatically select the first item from the results set for you, but additionally say you have multiple elements with that class name, but you know that there is only one element with that class name within a certain parent element, you can restrict the search to within that parent element, e.g. document.querySelector("#parent-div .gbts").

See the (Mozilla documentation) for more info.

Upvotes: 1

Arran
Arran

Reputation: 25056

You are asking how to get an element by it's CSS class using JavaScript. Nothing to do with Selenium really.

Regardless, you have a few options. You can first grab the element using Selenium (so here, yes, Selenium is relevant):

element = driver.find_element_by_class_name("gbts")

With a reference to this element already, it's then very easy to give it a border:

driver.execute_script("arguments[0].style.border = '1px solid red';")

(Note, the arguments[0])

If you really must use JavaScript and JavaScript alone, then you are very limited. This is because there is no getElementByClassName function within JavaScript. Only getElementsByClassName which means it would return a list of elements that match a given class.

So you must specifically target what element within the list, that is returned, you want to change. If I wanted to change the very first element that had a class of gbts, I'd do:

driver.execute_script("document.getElementsByClassName('gbts')[0].style.border = '1px solid red';")

I would suggest you go for the first option, which means you have Selenium do the leg work for you.

Upvotes: 4

Related Questions