blog

HTML Slot is one of the most remarkable standards made by W3C. Combine that with another impressive W3C standard called templates, and you have a fabulous concoction to work with. Being able to create and add HTML elements to a page using JavaScript is a necessary and important task.

It’s useful when a code snippet has to appear only at certain times, or when you don’t want to type out hundreds of similarly structured HTML elements but want to automize the process.

Creating HTML elements in JavaScript is not so desirable. It’s a hassle having to check and recheck if you have covered all the tags, placed them in the right order, all in all, there is just too much to type and keep track of. This turmoil, however, got a solution when the <template> tag appeared. If something needs to be added to the page dynamically, you can put it inside of the <template> element.

In this post, I will show you how you can use the <slot> and <template> tags together with JavaScript to create a mini HTML table factory that can create and populate hundreds of similar tables.

The <slot> and <template> tags

The <template> tag holds HTML code that won’t be rendered by browsers until it’s properly added to the document, using JavaScript. The <slot> tag is a placeholder you add to a Shadow DOM which can be made of the content of the <template> element.

A Shadow DOM is similar to a regular DOM (the document model parsed from HTML). It creates a scoped tree (a Shadow DOM tree), that has a root of its own and can also have a style of its own.

When you insert the Shadow DOM tree into an element in the main document — the element will then be called the shadow host —, all the child elements of the shadow host that are marked with the slot attribute (not the same as the aforementioned <slot> tag) will take their place in the newly inserted subtree.

The Shadow DOM, as of writing this article (July 2017), are supported only in WebKit- and Blink-based browsers but you can check the actual state of browser support on CanIUse at any time.

Setting up the HTML <template>

Still confusing? Let’s see some code, starting with the <template> element.

Inside <template>, there’s a <table> we’ll use as a blueprint for creating some tables that’ll be added to a document. There are <slot> elements inside the table cells (<th> and <td>) acting as placeholders for the column titles and cell values. Each slot has a unique name attribute that identifies it.

MAKE THE RIGHT CHOICE

We are passionate about innovation, ideas and experience. Tell us about yourself and your project and we can start the ball rolling.



By pressing "request quote", you are permitting us to contact you in relation to your enquiry and confirm that you have read and agree to our Privacy Policy.