Can I access the custom html content of the <component> or <slot> tag

Let's say I want to create a custom html element, for example:

<video-container> <video></video> </video-container> 

So, I create a template like this:

 <div class="wrapper"> etc.. <content></content> </div> 

Then I attach it to the page through the prototype HTML element createdCallback .

Inside this callback, I want to be able to attach listeners to the video element so that I can do things on play , pause , etc. It’s not clear to me if there is access to the video tag at all. I can access the content tag, but it does not display child nodes. Is it possible?

I can access the video element if I just grab the entire document and get the video element, but this is ugly because I want to be able to get only the video tag in the real user element area.

+6
source share
1 answer

Straight way

You should access it using querySelector for the most custom item:

 VideoContainerPrototype.createdCallback = function () { var video1 = this.querySelector( 'video' ) } 

You do not need to go past the Shadow DOM.


Shadow path

But if you want to get it from the root of the shadow, you can use the assignedNodes() method for your <slot> element (previously getDistributedNodes() on <content> ):

 var video2 = this.shadowRoot.querySelector( 'slot' ).assignedNodes()[1] 

It returns an array of nodes that have been inserted. Because in your example there is Node text at index [0] , you will need to get Node at [1] .

Note. You can also use named slots if you want to get your <video> element at index [0].

+7
source

All Articles