0

I am getting a JavascriptException trying to execute some JavaScript code on chrome driver, i am pretty confident the JS code is correct but I get:

 raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.JavascriptException: Message: javascript error: document.getElementByClassName is not a function
  (Session info: chrome=110.0.5481.178)

My code:

driver.execute_script("document.getElementByClassName('hand card-stack fanned loose rotate-bottom ui-droppable').classList.add('selectedstack');")
elms = WebDriverWait(driver, 0.5).until(EC.presence_of_all_elements_located((By.XPATH, cards)))
for elm in elms:
    driver.execute_script("arguments[0].setAttribute('class','selectedcard')", elm)
    driver.execute_script("arguments[0].click();", elm)

2 Answers2

1

Use getElementsByClassName, There's no such method as getElementByClassName.

You code should be something like:

driver.execute_script("document.getElementsByClassName('hand card-stack fanned loose rotate-bottom ui-droppable')[0].classList.add('selectedstack');")
    elms = WebDriverWait(driver, 0.5).until(EC.presence_of_all_elements_located((By.XPATH, cards)))
    for elm in elms:
        driver.execute_script("arguments[0].setAttribute('class','selectedcard')", elm)
        driver.execute_script("arguments[0].click();", elm)
Pruthvi Raj
  • 3,016
  • 2
  • 22
  • 36
0

getElementsByClassName()

The getElementsByClassName() method of Document interface returns an array-like object of all child elements which have all of the given class name(s).

So instead of getElementByClassName() you should be using getElementsByClassName() and supply the index [0] as follows:

driver.execute_script("document.getElementsByClassName('hand card-stack fanned loose rotate-bottom ui-droppable')[0].classList.add('selectedstack');")

Additionally, as you are setting attribute values and invoking click on the elements within the list elms, instead of presence_of_all_elements_located() you need to induce WebDriverWait for the visibility_of_all_elements_located() as follows:

elms = WebDriverWait(driver, 0.5).until(EC.visibility_of_all_elements_located((By.XPATH, cards)))

So your effective code block will be:

driver.execute_script("document.getElementsByClassName('hand card-stack fanned loose rotate-bottom ui-droppable')[0].classList.add('selectedstack');")
elms = WebDriverWait(driver, 0.5).until(EC.visibility_of_all_elements_located((By.XPATH, cards)))
for elm in elms:
    driver.execute_script("arguments[0].setAttribute('class','selectedcard')", elm)
    driver.execute_script("arguments[0].click();", elm)
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352