Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Web Components: Building Custom Elements with JavaScript
Next article icon

Web Components: Building Custom Elements with JavaScript

Last Updated : 27 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

In web development, creating reusable and encapsulated components is crucial for building scalable and maintainable applications and Web Components offer a powerful solution to this challenge by providing developers with the ability to build custom HTML elements with their functionality and styling. This article introduces Web Components and explores how they can enhance the development process and make it easier to create modular and reusable code.

Web Components are a set of web platform APIs that allow you to create custom, reusable, and encapsulated components for building web applications components can be used on any web page regardless of the framework or library being used and promote a modular and standardized approach to web development.

 They consist of two main specifications:

Table of Content

  • Using Custom Elements with Shadow DOM
  • Using HTML Templates

Approach 1: Using Custom Elements with Shadow DOM

Creating custom web components using the Shadow DOM is a modern approach to building reusable and encapsulated UI elements for your web applications. Custom elements with the Shadow DOM offer a way to define your own HTML elements.

Syntax:

class MyCustomElement extends HTMLElement {  }  customElements.define('my-custom-element', MyCustomElement);  

Example: This example shows the use of the above-explained approach.

HTML
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <title> Custom Element </title>     <style>         h1 {             color: #336699;         }     </style> </head>  <body style="background-color: #C0C0C0;">     <my-custom-element></my-custom-element>     <script> class MyCustomElement extends HTMLElement {             constructor() {                 super();                 const shadowRoot =                        this.attachShadow({ mode: 'open' });                 const paragraph =                        document.createElement('p');                 paragraph.textContent =                    '**This is custom element with Shadow DOM**';                 shadowRoot.appendChild(paragraph);                 const style = document.createElement('style');                 style.textContent = `           p {             color: red;           }         `;                 shadowRoot.appendChild(style);             }         }         customElements.define('my-custom-element', MyCustomElement);     </script> </body>  </html> 

Output:

Screenshot-2023-07-27-203514

Approach 2: Using HTML Templates

The HTML templates provide an innovative way to wield logical subsetting techniques in R, offering a dynamic and interactive approach to data manipulation and integrating HTML templates you can create visually engaging reports that allow users to interact with the data selecting subsets based on their criteria.

Syntax:

class MyCustomElement extends HTMLElement {      constructor() {          super();          const template = document.getElementById('custom-template').content;          const shadowRoot = this.attachShadow({ mode: 'open' });          const clonedTemplate = document.importNode(template, true);          shadowRoot.appendChild(clonedTemplate);      }  }  

Example: This example shows the use of the above-explained approach.

HTML
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <title>Templates</title>     <style>         h1 {             color: #336699;         }     </style> </head>  <body style="background-color: #FFFF00;">     <template id="custom-template">         <p>               **This is custom element with HTML Templates**           </p>     </template>     <my-custom-element></my-custom-element>     <script>         class MyCustomElement extends HTMLElement {             constructor() {                 super();                 const template =                        document.getElementById('custom-template').content;                 const shadowRoot =                        this.attachShadow({ mode: 'open' });                 const clonedTemplate =                        document.importNode(template, true);                 shadowRoot.appendChild(clonedTemplate);             }         }         customElements.define('my-custom-element', MyCustomElement);     </script> </body>  </html> 

Output :

Screenshot-2023-07-27-203859


Next Article
Web Components: Building Custom Elements with JavaScript

M

mguru4c05q
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-basics

Similar Reads

    JavaScript code for adding new elements in a dynamic way
    Javascript is a very important language when it comes to learning how the browser works. Often there are times we would like to add dynamic elements/content to our web pages. This post deals with all of that. Creation of new element: New elements can be created in JS by using the createElement() met
    2 min read
    Build an AI Image Generator Website in HTML CSS and JavaScript
    Create an AI image generator website using HTML, CSS, and JavaScript by developing a user interface that lets users input text prompts and generate images by AI.We incorporated API integration to fetch data, providing users with an effortless and dynamic experience in generating AI-driven images. An
    4 min read
    How to select DOM Elements in JavaScript ?
    Selecting DOM (Document Object Model) elements is a fundamental aspect of web development with JavaScript. It allows developers to interact with and manipulate elements on a webpage dynamically. Proper selection of elements is crucial for tasks such as updating content, adding event listeners, or mo
    3 min read
    Manipulating HTML Elements with JavaScript
    JavaScript is a powerful language that can be used to manipulate the HTML elements on a web page. By using JavaScript, we can access the HTML elements and modify their attributes, styles, and content. This allows us to create dynamic and interactive web pages. Methods to Identify the elements to man
    5 min read
    How to Create a Chips Component using HTML CSS & JavaScript ?
    In this article, we will see how we can create a chip component with the help of HTML, CSS, and JavaScript. In a chip component, there are basically two sections: one is the content section, and the other is the cross-button section. Both should be under one container with a proper border-radius. Pr
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences