I want to hide elements on canvas element by executing a javascript in python.
I have tried below:
def hide_elements():
driver = LiveLibrary.get_webdriver_instance()
js_script = '''\
element1 = document.getElementsByClassName('someclass');
element1[0].style.display = 'none';
element2 = document.getElementsByClassName('another');
element2[0].style.display = 'none';
element3 = document.getElementsByClassName('highlight');
element3[0].style.display = 'none';
element4 = document.getElementsByClassName('overlay');
element4[0].style.display = 'none';
'''
driver.execute_script(js_script)
The above works but as you can see there is a repetition of code. Is there a way I can simplify this rather than finding each element and hiding them?
If only one of each class - I use ES<5 to not break your webdriver:
var cls = ["someclass","another","highlight","overlay"];
for (var i=0;i<cls.length;i++) {
document.querySelector("."+cls[i]).style.display = "none";
}
This would work in a browser:
[...document.querySelectorAll("[class^=class]")].forEach(ele => ele.style.display = "none");
For different classes:
["someclass","another","highlight","overlay"]
.forEach(cls => [...document.querySelectorAll("."+cls)]
.forEach(ele => ele.style.display = "none"));
For older JS versions:
["someclass","another","highlight","overlay"]
.forEach(function(cls) { [...document.querySelectorAll("."+cls)]
.forEach(function(ele) { ele.style.display = "none"})});
Even older:
var cls= ["someclass","another","highlight","overlay"];
for (var i=0;i<cls.length;i++) {
var elements = document.querySelectorAll("."+cls[i]);
for (var j=0;j<elements.length;j++) {
elements[j].style.display = "none";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With