如何在Selenium中查找元素并添加类(使用JavaScript)?

huangapple go评论82阅读模式
英文:

How to find element and add class in selenium js?

问题

我尝试在JavaScript中使用classList.add方法,但没有成功 😞

await driver.findElement(By.css(".promotion-code-group.promo-shown .promo-selector")).classList.add("show");

TypeError: 无法读取未定义的属性 'add'

我需要你在Selenium JavaScript方面的知识,希望你们可以指导我。提前感谢你们!

英文:

How can we perform add class to a specific element?

I tried classList.add method in javascript but no luck 😞

await driver.findElement(By.css(".promotion-code-group.promo-shown .promo-selector")).classList.add("show");

TypeError: Cannot read property 'add' of undefined

I need your knowledge in selenium js I hope you guys can guide me through this. Thank you guys in advance!

答案1

得分: 1

你可以使用execute_script()函数编辑一个元素的类列表。

setAttribute()的第二个参数中,你应该放入现有的类以及新添加的类:

const element = await driver.findElement(
   By.css(".promotion-code-group.promo-shown.promo-selector")
);

await driver.execute_script(
   "arguments[0].setAttribute('class', 'promotion-code-group promo-shown show')", 
   element
);
英文:

You can edit an element's class list using execute_script() function.

In the second argument in setAttribute() you should put existing classes plus the new ones:

const element = await driver.findElement(
   By.css(".promotion-code-group.promo-shown promo-selector")
);

await driver.execute_script(
   "arguments[0].setAttribute('class', 'promotion-code-group promo-shown show')", 
   element
);

huangapple
  • 本文由 发表于 2023年1月9日 16:22:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75054680.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定