Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide elements using selenium webdriver in python by executing a javascript

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?

like image 564
someuser2491 Avatar asked Apr 07 '26 14:04

someuser2491


1 Answers

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";
  }
}
like image 141
mplungjan Avatar answered Apr 09 '26 03:04

mplungjan