Menu

A web component without Shadow DOM: build one with plain JavaScript
πŸ“°

A web component without Shadow DOM: build one with plain JavaScript

DEV Community: javascriptΒ·Andrzej StacherskiΒ·5 days ago
#WHVyDl9B
#devtojavascript#devto#dev#fact#topic
Reading 0:00
15s threshold

Build a custom element with plain JavaScript and plain CSS: lifecycle, properties vs attributes, and the two traps that break most first components.

Most web component tutorials open with Shadow DOM, templates and slots. You can skip all of that and still get a useful, reusable component. Here is a card element in vanilla JavaScript. It works with your normal CSS and needs no build step.

The goal is to turn this:

const card = document . createElement ( 'article' ) ; card . className = 'card' ; // ...a dozen lines of createElement and append

Enter fullscreen mode

Exit fullscreen mode

into this:

const card = document . createElement ( 'ml-card' ) ; card . fact = fact ; card . topic = topic ; feed . append ( card ) ;

Enter fullscreen mode

Exit fullscreen mode

And in HTML, you can write <ml-card hint></ml-card> as if browsers had always shipped a card tag.

Two details in that tag are worth explaining up front:

ml- is a prefix I use on every component.…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.