Found a new JS pattern from MSDN.
One day, I was trying to detect whether an element is an element that has no close tag.
So I did this:
var tagName = el.tagName.toLowerCase();
if( tagName == ‘img’ || tagName == ‘br’ || tagName == ‘input’ || tagName == ‘embed ‘ ){
// This is just a example, not all single tags are tested. These tags are :
// area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed.
// Do something here.
}
Well, this is not that efficient to write your program.
So I switch to use a string map, which is rather simple and John Resig uses the same trick in his HTML Parser.
var map = makeMap(’area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed’);
if( map[tagName]){
// Do something here.
}
Of course we can use RegExp to test it, just like many others did.
var reg = /^(area|base|basefont|br|col|frame|hr|img|input|isindex|link|meta|param|embed)$/i;
var tagName = ‘BR’;
if( reg.test(tagName)){
// Do something…
}
and maybe you can find more tricks that solve the same problem with low cost, but below is the most interesting one that caught my attention.
if ( tagName != “BUTTON” | “B” | “A” ){
// Do something…
}
Wait, this seems really strange to me and seems not to perform as what I was expecting.
However, since I found this code snippets from MSDN, there must be something magic which makes this working.
Unfortunately, this is simply not working though I almost thought I found a new JS pattern from MSDN and was very excited about it for just about 10 seconds.
It’s fun to learn JS from microsoft.