Custom HTML Tags using JavScript

Custom Tags in HTML using JavaScript.

Browsers allow us to use a predefined set of HTML tags. There are times when we want to use our own tags in our html documents.

Custom tags in server side scripting

Server side scripting languages have the feature of adding our own tags to the server side scripts such as jsp. For example we use jsp tag libraries to achieve this in java. There is no big magic in this. The tag library actually prints a creates a HTMl code snippet for the given tags and replace the original html with these constructed HTML. The custm tag is converted to html before it is seen by the browser. But at the end the browsers see only predefined html tags.

Custom tag in JavaScript

Is it possible to make the browser react to a custom tag when it encounters such one in the DOM?

This is possible using JavaScript, when the browser encounters your custom tag, it can handl it like any other valid predefined tag.

Consider we have custom tag  <mytag id="mtag" txt="google"  url=""> To go to google click </mytag>
we will let the browser process these tags as below

To go to google click google

A complete example is below.
// function to trigger onload
  function p(){
   var a =   document.getElementsByTagName("mytag");
   var obj = null;
     obj = new mytag(a[i]);
//process custom tag mytag
  function mytag(c){
   var txt = null;
   var url = null;
   if(typeof c.attributes.type != null){
    for(k = 0; k < c.attributes.length; k++){
      var attrib = c.attributes[k];
          if( == 'txt'){
         txt = attrib.value;
      }else if( == 'url'){
         url = attrib.value;
    } //for              
   this.f = document.createElement('span');
   this.f.innerHTML = "<a href='"+url+"'>"+txt+"</a>";
<body onload="p()">
 <mytag id="mytag1" txt="google"  url=""> To go to google click </mytag> <br/>
 <mytag id="mytag2" txt="yahoo" url="">To go to yahoo click </mytag>


  1. Good post! Easy example!! Thanks!!!

  2. This method does not work in IE7 (line 29).

    1. Known issue with IE, You may want to use as,
      <span><mytag txt="google" url=""></mytag> </span>

      Now use  tag.parentNode.appendChild(t);  instead tag.appendChild(t);


Post a Comment

Popular posts from this blog

Log4j multiple WAR files in single EAR configuration

Ubuntu / kubuntu - Laptop key board cursor jumping issue

Java NIO2 - Watching a directory for changes. FileWatcherService.