Open In App

HTML slot Attribute

The HTML <slot> element allows users to create shadow DOM (Document Object Model). The shadow tree is a collection of elements in a particular order. If users need to create the web components with the same structure often, they can create a shadow tree using the <slot> element. In simple words, the <slot> HTML element is a Web component which is a placeholder, placed inside the web component that facilitates filling the makeup with own choice which will help to create separate DOM trees and represent them together. The user can use create the shadow tree using the template tag. Here, the structure of the shadow tree remains fix but users can add any HTML element at a particular slot location.

Users can access the particular slot in the template using its name attribute. The below syntax describes the <slot> element:



Syntax:

<slot name='exampleSlot'></slot>

Attributes: The <slot> element includes following attributes:



We can access the above slot element from the shadow tree like below:

<h1 slot='exampleSlot'>GeeksforGeeks</h1> 

We can fit any HTML element to the slot location using the name attribute.

This example illustrates how the browser parsed the <slot> element:

 <div class="website">
  <div class="webpage">
    <h1 slot="webpageName">GeeksforGeeks</h1>
  </div>
  <div>
    <h3 slot="webpageDesc">Computer science portal</h3>
    <img src=
"https://media.geeksforgeeks.org/wp-content/uploads/20210915115837/gfg3-300x300.png" 
           slot="webpageImage">
  </div>
</div>

In the browser, the below HTML code behaves like this illustrated code. By adding a slot attribute to an element, we are providing a slot to that element in the shadow tree. As you can see, it fits in a specific slot within the shadow tree. 

Example: This example describes the basic usage of the slot attribute.




<!DOCTYPE html>
<html>
 
<head>
    <title>Slot element</title>
</head>
 
<body>
    <div class="website">
        <div class="webpage">
             
            <!--Creating slot element-->
            <slot name="webpageName"></slot>
        </div>
        <div>
            <slot name="webpageDesc"></slot>
            <slot name="webpageImage"></slot>
        </div>
    </div>
    <user-data>
         
        <!--Accessing the slot element by name
      and adding markup elements-->
        <h1 slot="webpageName">GeeksforGeeks</h1>
        <h3 slot="webpageDesc">Computer science portal</h3>
            <img src=
                 slot="webpageImage">
    </user-data>
</body>
 
</html>

Output: For the output, the elements are fitted in the shadow tree. 

Supported Browsers: The <slot> element supports the below browsers.


Article Tags :