How to create custom tags for HTML
There's an interesting and in depth article from HTML5Rocks.com on how to work with custom elements : Custom Elements: Defining New Elements in HTML
Here's an excerpt from the article on how to do it.
Instantiating elements
The common techniques of creating elements still apply to custom elements. As with any standard element, they can be declared in HTML or created in DOM using JavaScript.
Instantiating custom tags
Declare them:
<x-foo></x-foo>
Create DOM in JS:
var xFoo = document.createElement('x-foo');
xFoo.addEventListener('click', function(e) {
alert('Thanks!');
});
Use the new operator:
var xFoo = new XFoo();
document.body.appendChild(xFoo);
custom HTML tags and attributes
I ran your code and it worked just fine with the constructor
, but you could try connectedCallback
instead. This method gets called any time an element is added to the document.
Make sure your script runs in the <head>
of the document, before your <body>
is executed. HTML/scripts run top-to-bottom. Your element needs to be registered before it is rendered.
Update: Please refer to the "Custom elements" - JavaScript.info article that was linked by Martin Braun for a better understanding. The official MDN documentation can be viewed here: "Using custom elements" - MDN.
class MyTrophy extends HTMLElement {
connectedCallback() {
const rarity = this.getAttribute('rarity');
console.log(`Rarity: ${rarity}`);
}
}
customElements.define('my-trophy', MyTrophy);
my-trophy {
font-size: 3em;
}
my-trophy[rarity="silver"] {
color: #777;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" rel="stylesheet"/>
<my-trophy class="fas fa-trophy" rarity="silver"></my-trophy>
Create custom tags/attributes using JavaScript
Why yes, yes you can. In fact, they're a stable part of the web components standard.
Custom Elements is a capability for creating your own custom HTML
elements. They can have their own scripted behavior and CSS styling.
They are a part of web components, but can also be used by themselves.It may be unclear as to why the new custom elements capability was
created, as it was already possible to create a tag name like<mytag>
and style it with CSS, then use scripting to attach behaviors to it.
An advantage that custom elements have are their lifecycle reactions,
which allow attaching behaviors to different parts of the new
element's "lifecycle." For example, a certain behavior can be attached
for when the element is inserted into the DOM ("connected"), and a
different behavior when it is removed from the DOM ("disconnected"),
or when its attributes change.
Example
// Create a class for the elementclass XProduct extends HTMLElement { constructor() { // Always call super first in constructor super();
// Create a shadow root var shadow = this.attachShadow({mode: 'open'});
// Create a standard img element and set its attributes. var img = document.createElement('img'); img.alt = this.getAttribute('data-name'); img.src = this.getAttribute('data-img'); img.width = '150'; img.height = '150'; img.className = 'product-img';
// Add the image to the shadow root. shadow.appendChild(img);
// Add an event listener to the image. img.addEventListener('click', () => { window.location = this.getAttribute('data-url'); });
// Create a link to the product. var link = document.createElement('a'); link.innerText = this.getAttribute('data-name'); link.href = this.getAttribute('data-url'); link.className = 'product-name';
// Add the link to the shadow root. shadow.appendChild(link); }}
// Define the new elementcustomElements.define('x-product', XProduct);
body { background: #F7F7F7;}
x-product { display: inline-block; float: left; margin: 0.5em; border-radius: 3px; background: #FFF; box-shadow: 0 1px 3px rgba(0,0,0,0.25); font-family: Helvetica, arial, sans-serif; -webkit-font-smoothing: antialiased;}
x-product::slotted(.product-img) { cursor: pointer; background: #FFF; margin: 0.5em;}
x-product::slotted(.product-name) { display: block; text-align: center; text-decoration: none; color: #08C; border-top: 1px solid #EEE; font-weight: bold; padding: 0.75em 0;}
If nothing appeared below, then your browser does not support Custom Elements yet.<x-product data-name="Ruby" data-img="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4621/ruby.png" data-url="http://example.com/1"></x-product><x-product data-name="JavaScript" data-img="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4621/javascript.png" data-url="http://example.com/2"></x-product><x-product data-name="Python" data-img="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4621/python.png" data-url="http://example.com/3"></x-product>
Is there a way to create your own html tag in HTML5?
You can use custom tags in browsers, although they won’t be HTML5 (see Are custom elements valid HTML5? and the HTML5 spec).
Let's assume you want to use a custom tag element called <stack>
. Here's what you should do...
STEP 1
Normalize its attributes in your CSS Stylesheet (think css reset) -
Example:
stack{display:block;margin:0;padding:0;border:0; ... }
STEP 2
To get it to work in old versions of Internet Explorer, you need to append this script to the head (Important if you need it to work in older versions of IE!):
<!--[if lt IE 9]>
<script> document.createElement("stack"); </script>
<![endif]-->
Then you can use your custom tag freely.
<stack>Overflow</stack>
Feel free to set attributes as well...
<stack id="st2" class="nice"> hello </stack>
Is it safe to create Custom HTML Tags?
@PrisonerZER0 I wouldn't call "Olde browsers" the word "safe". Somewhat of an oxymoron. Even M$ has put IE in a coffin. https://www.microsoft.com/en-us/windowsforbusiness/end-of-ie-support
Us supporting them is only asking for trouble. Thanks for the shout.
I created the snuggsi ツ
(https://github.com/devpunks/snuggsi) library as a suite of conventions over the web components/custom elements native browser spec. My philosophy is you shouldn't need to know node, webpack, babel, etc. Should only need to know basic HTML,CSS,JS to be productive in 2017. The following snippet is a perfect example.
Feel free to reach out on github as it seems like you are up to snuff with modern platform development. We won't need these convoluted front end tools where we are going Feel free to reach out on github so i can help you get started!
<hello-world> Hello {planet}</hello-world>
<!-- more info @ https://github.com/devpunks/snuggsi --><script src=//unpkg.com/snuggsi></script><script>
// Element Definition -----------------------------
Element `hello-world`
// Class Description ------------------------------
(class extends HTMLElement {
get planet () // "automagic" token binding { return 'world ' }
onclick () // "automagic" event registration { alert (this) }})
</script>
Create custom tags html
You can so something like this:
redbox {
display: block;
width: 100px;
height: 100px;
background-color: red;
}
<redbox></redbox>
<!-- OR -->
<redbox />
Using custom HTML Tags
It is best to avoid using custom tags, as you never know when those tags may become standardized, and have special usage in the future.
The best thing to do for your example, if you want to avoid using the header tags, is the following:
<div class="toys grid_4 push_2"> </div>
.toys {
background: url("toys.png") no-repeat scroll 0 0 transparent;
width: 181px;
height: 93px;
margin-top: -8px;
}
In addition:
If you do not use standard html tags when designing pages, they will not appear in any organized manner when styles are disabled. This is not a problem, going forward, but if for any reason you needed to view a list of "toys" without styles, you had be out of luck unless you use <ul>
or <ol>
with <li>
tags.
UPDATE:
As Flimzy pointed out in the comments, custom HTML elements now have their own W3C specification. However, they are not yet fully supported.
- Specification: https://www.w3.org/TR/custom-elements/
- Support: http://caniuse.com/#feat=custom-elements
Is it bad practice to define a custom HTML tag
Creating custom HTML tags are perfectly fine nowadays, however, you need to know how to properly create them, for a better browser support. Make sure they have a "meaning", or "role" for better readability. It is great when working with web components.
Here is a good article about creating custom html elements:
https://www.smashingmagazine.com/2014/03/introduction-to-custom-elements/
Related Topics
How to Choose Between 'Class' and 'Id'
Nesting ≪P≫ Won't Work While Nesting ≪Div≫ Will
How to Trigger Autofill in Google Chrome
How to Make Div Elements Display Inline
Placing Border Inside of Div and Not on Its Edge
What's the Valid Way to Include an Image With No Src
Limit Scope of External CSS to Only a Specific Element
Position Footer At Bottom of Page Having Fixed Header
How to Encode/Decode HTML Entities in Ruby
Invert CSS Font-Color Depending on Background-Color
How to Make Html5 Video Fullscreen
Uri Starting With Two Slashes ... How Do They Behave
Svgs Not Scaling Properly in Ie - Has Extra Space
How to Remove Underline from a Link in Html
How to Fallback to Local Stylesheet (Not Script) If Cdn Fails