Open In App

HTML slot Attribute

Last Updated : 01 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 create the shadow tree using the template tag. Here, the structure of the shadow tree remains fixed 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:

  • name: It defines the name of a particular slot in the shadow tree. It should be unique.

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.

HTML
<!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=
"https://media.geeksforgeeks.org/wp-content/uploads/20210915115837/gfg3-300x300.png" 
                 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.


Next Article
Article Tags :

Similar Reads