Search code examples
javascripttampermonkeyshadow-dom

Hide div inside (e.g. Twitter) shadow-dom with JavaScript


Using TamperMonkey to streamline page view on my side, and wish to hide part of the externally-sourced Twitter card(s) from printing. The image in the EmbeddedTweet does not print anyway, and leaves a large empty rectangle that wastes valuable space.

The DOM looks like the image below - how would I target the DIV with class SummaryCard-image (green arrow)? It doesn't matter to me if the DIV is removed from the DOM, or just hidden with CSS.

I have tried the below methods, which do not work:

(1) Injecting CSS with .SummaryCard-image{display:none !important;}

(2) jQuery: $('.SummaryCard-image').remove();

$('.SummaryCard-image').length returns 0

(Note the #shadow-root (open), 2nd element from the top)

enter image description here


Solution

  • You need to select the shadow root first inorder to traverse to that element. You need something like this

    var twitterWidget= document.querySelector('twitterwidget').shadowRoot;
    twitterWidget.querySelector('.SummaryCard-image').style.display = "none";
    

    For multiple twitter widgets

        var twitterWidgets = document.querySelectorAll('twitterwidget'); 
    
        twitterWidgets.forEach(function(item){
          var root = item.shadowRoot; root.querySelector('.SummaryCard-image').style.display = 'none';
        })
    

    Example https://rawgit.com/ebidel/2d2bb0cdec3f2a16cf519dbaa791ce1b/raw/fancy-tabs-demo.html

    var tabs= document.querySelector('fancy-tabs').shadowRoot
    tabs.querySelector('#tabs').style.display = none