Zum Hauptinhalt springen
tsecurity.de LIVE
Echtzeit-Radar & Feeds
Alle RSS Feeds
👥 Community & Social
YouTube Security VideosGoogle Cloud Tech: Vibe coding in the pit lane 🏁(23.09.2026 um 01:00 Uhr)
Sichere ProgrammierungBuild an Explainable Vendor-Risk Gate in Node.js(23.09.2026 um 00:27 Uhr)
Sichere ProgrammierungFrom p=none to Enforcement: A Working Sequence for DMARC Rollout(23.09.2026 um 00:40 Uhr)
Sichere ProgrammierungWhen OPA's Bundle Loader Runs Past a `.manifest` Typo(23.09.2026 um 00:53 Uhr)
Sichere ProgrammierungGovernance Attack Surface Review: Bybit(23.09.2026 um 01:00 Uhr)
Linux Tipps & HardeningOpenShot video editor is now available as a snap(23.09.2026 um 00:09 Uhr)
KI & AI VideosAI Revolution: AI Robots Are Beating Humans Now(23.09.2026 um 00:32 Uhr)
YouTube Security VideosGoogle Cloud Tech: Vibe coding in the pit lane 🏁(23.09.2026 um 01:00 Uhr)
Sichere ProgrammierungBuild an Explainable Vendor-Risk Gate in Node.js(23.09.2026 um 00:27 Uhr)
Sichere ProgrammierungFrom p=none to Enforcement: A Working Sequence for DMARC Rollout(23.09.2026 um 00:40 Uhr)
Sichere ProgrammierungWhen OPA's Bundle Loader Runs Past a `.manifest` Typo(23.09.2026 um 00:53 Uhr)
Sichere ProgrammierungGovernance Attack Surface Review: Bybit(23.09.2026 um 01:00 Uhr)
Linux Tipps & HardeningOpenShot video editor is now available as a snap(23.09.2026 um 00:09 Uhr)
KI & AI VideosAI Revolution: AI Robots Are Beating Humans Now(23.09.2026 um 00:32 Uhr)
Intelligence View
⚡ tsecurity.de Intelligence

How to Build a Simple Web Component from Scratch

Web components are a set of powerful tools that allow you to create your own custom HTML elements. These elements can be used just like any other HTML tag (e.g., <div>, <span>) but with your own special behavior and…

0
↗ Quelle (dev.to)
Reagiere als Erste:r — dein Feedback zählt!

Web components are a set of powerful tools that allow you to create your own custom HTML elements. These elements can be used just like any other HTML tag (e.g., <div>, <span>) but with your own special behavior and design.



The core technologies behind web components are:





  • Custom Elements: Allows you to define new HTML tags.


  • Shadow DOM: Keeps your element’s structure and styles isolated from the rest of the page.


  • HTML Templates: Lets you define reusable HTML that isn’t rendered until you use it.



In this guide, we'll build a simple counter component from scratch. This counter will have buttons to increase and decrease a number.



The component will look like this:



Image description



Here is the link for final version with all the source code.









Prerequisites



Before we begin, here’s what you need to know:




  • Basic JavaScript.

  • A simple understanding of how the DOM (Document Object Model) works (don’t worry if you’re not an expert — we’ll cover what you need).









Setting Up the Project



First, let’s set up a simple project with two files:





  1. counter.html: The HTML file that will hold the page structure.


  2. counter.js: The JavaScript file where we define our custom counter element.






counter.html



This file contains the basic HTML structure of your page:




<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<title>Counter Component</title>
<script src="./counter.js"></script>
</head>
<body>
<!-- The counter component will be inserted here -->
</body>
</html>












Creating the Template



A template is just a way to define the structure of our custom element (like what it looks like). Let’s create one for our counter:






counter.html (Add the Template)






<body>
<template id="x-counter">
<div>
<button id="min-btn">-</button>
<span id="counter-display">0</span>
<button id="plus-btn">+</button>
</div>
</template>
</body>






Here’s what each part of this template does:





  • <button id="min-btn">-</button>: A button to decrease the counter.


  • <span id="counter-display">0</span>: A place to show the current counter value.


  • <button id="plus-btn">+</button>: A button to increase the counter.



This template will not show up on the page directly. We will use it later to create our custom element.









Defining the Custom Counter Element



Now, we’ll write the JavaScript to define how our counter works. We’ll create a class that extends the basic HTMLElement, which is what all HTML elements are built on.






counter.js






class XCounter extends HTMLElement {
constructor() {
super();
this.counter = 0; // Start the counter at 0
this.elements = {}; // To store references to our buttons and display
}

connectedCallback() {
// This runs when the element is added to the page
const template = document.getElementById("x-counter");
this.attachShadow({ mode: "open" });

// Clone the template and add it to our custom element's shadow DOM
this.shadowRoot.appendChild(template.content.cloneNode(true));

// Get references to the buttons and display
this.elements = {
plusBtn: this.shadowRoot.querySelector("#plus-btn"),
minBtn: this.shadowRoot.querySelector("#min-btn"),
counterDisplay: this.shadowRoot.querySelector("#counter-display")
};

// Show the initial counter value
this.displayCount();

// Add event listeners for the buttons
this.elements.plusBtn.onclick = () => this.increment();
this.elements.minBtn.onclick = () => this.decrement();
}

increment() {
this.counter += 1;
this.displayCount();
}

decrement() {
this.counter -= 1;
this.displayCount();
}

displayCount() {
this.elements.counterDisplay.textContent = this.counter;
}
}

// Register the custom element so we can use it in HTML
customElements.define("x-counter", XCounter);









Breaking it Down:




  1. The constructor: This is where we set up initial values for our counter and store references to the elements inside the counter.



  2. connectedCallback: This function runs when the custom element is added to the page. Here, we:




    • Attach a shadow DOM to keep our element’s structure and styles separate from the rest of the page.

    • Clone the template we created earlier and add it to the shadow DOM.

    • Set up references to the plus and minus buttons and the display where the counter is shown.



  3. increment and decrement: These functions change the value of the counter by 1 and update the display.


  4. displayCount: This function updates the text inside the <span> to show the current counter value.


  5. Register the element: Finally, we tell the browser to recognize <x-counter> as a custom element that uses the XCounter class.










Using the Counter Component



Now that our counter is defined, we can use it just like any other HTML element. Here’s how to add it to the page:






counter.html (Add the Custom Element)






<body>
<x-counter></x-counter>

<template id="x-counter">
...
</template>
</body>






This will create a counter on the page with two buttons — one to increase and one to decrease the number. The counter will start at 0, and you can interact with it by clicking the buttons.









Style the element



Styling can be done in a few ways, but when using the Shadow DOM, we can encapsulate the styles to ensure they don’t interfere with other parts of the page. In this section, we will style our counter element using adopteStyleSheet.






counter.js with Styling






...
connectedCallback() {
...
this.attachShadow({ mode: 'open' });

// Add styles to the component
const sheet = new CSSStyleSheet();
sheet.replaceSync(this.styles());
this.shadowRoot.adoptedStyleSheets = [sheet];

// Clone the template and add it to our custom element's shadow DOM
this.shadowRoot.appendChild(template.content.cloneNode(true));
...
}
...
styles() {
return `
:host {
display: block;
border: dotted 3px #333;
width: fit-content;
height: fit-content;
padding: 15px;
}

button {
border: solid 1px #333;
padding: 10px;
min-width: 35px;
background: #333;
color: #fff;
cursor: pointer;
}

button:hover {
background: #222;
}

span {
display: inline-block;
padding: 10px;
width: 50px;
text-align: center;
}
`

}
...
...












Conclusion



In this tutorial, we learned how to create a simple web component:




  • We used an HTML template to define the structure of our custom element.

  • We added shadow DOM to isolate the styles and behavior of our component.

  • We wrote JavaScript to control the logic of the counter (increment, decrement, and display the count).



Web components are a great way to make your web applications more modular and reusable. Now that you know the basics, you can experiment with more complex components, like adding custom styles or animations to your elements.

Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten How to Build a Simple Web Component from Scratch

Thematisch verwandte Begriffe: Build, Simple, Component, from · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Zum Aktualisieren ziehen
ZERO-DAY CVE-2026-17636 | IBM Financial Transaction Manager (FTM) for RedHat OpenShift could allow…
Advisory →
TTS Reader • tsecurity.de Voice
tsecurity.de Icon
tsecurity.de App
Offline-Lesen, Eilmeldungen & 0ms Ladezeit

Installiere tsecurity.de direkt auf deinen Home-Bildschirm für das ultimative Vollbild-Magazinerlebnis ohne Browser-Leisten.

Nächster Beitrag
Themen-Radar & Intelligence Matrix
Echtzeit-Taxonomie nach Angriffsvektoren & Plattformen

tsecurity.de Live Threat Radar

🔴 LIVE RADAR
MONITORING
AKTIV
CVE-DATENBANK
LIVE
🔍
Community Radar & Live Chat
Sentinel Bot online • Live-Stream
Dein Cluster: Security Explorer
Match:
lädt…
Verbindung zum Community-Stream wird aufgebaut...
Bearbeitungsmodus — Senden überschreibt deine Nachricht
Community-Puls — was gerade passiert
lädt…
Aktivitäten deiner Analysten
lädt…
Neues Thema oder Eilmeldung einreichen

Reiche interessante Links, Zero-Days oder Debatten ein. Die Community entscheidet per Upvote über die Veröffentlichung.

Heiß diskutierte Einreichungen
🔖 Gespeicherte Artikel
📂 Keine gespeicherten Artikel vorhanden.
Zurück Ziehen Vor
Links: vorheriger Artikel Rechts: nächster Artikel unten: schließen
News NIS-2 Frühwarnung Tier-1 Intel ⏱️ 3 Min vor 10 Min
Artikeldaten werden geladen...

Zurück: vorheriger Vor: nächster
↗ Original-Quelle
Social Reaktionen Deine Reaktion zählt
Einstufung & Relevanz-Poll 0 Stimmen
In sozialen Netzwerken teilen 1-Klick