July 18, 2011

HTML Comments are diamonds

So everyone thinks that html comments are lame... well... they are NOT! They can be extremely useful! In fact...

$("*").contents().filter(function()
 { return this.nodeType == 8;})
 .after(function(){return this.data})

- Ta-da
- What?
- What did you do that was so "ta-da"?
- Well, using jQuery i just converted all the comments content into actual HTML, so if someone had <!-- <h1>Haters gonna hate</h1> --> it will transform into actual HTML!
- And why would i want to do that?
- You know that comments don't get read by the Google Search bot, right?
- Yeah....
- Well, ajax is cool and all that... but is always faster if the content is already on the current page
- Yeah...
- Mmmm... do i need to make you a drawing or something dude?
- F*ck you.

I know some of you are lame as sh*t and don't love the all-mighty jQuery javascript library so here it is the same code in 100% pure cross-browser javascript (IE7+, Chrome, Firefox):


function find_comments(selection)
{
 selection = selection || document
 comments_found=[];
 loop(selection.childNodes)
 function loop(arr)
 {
  for(var i = 0; i<arr.length;i++)
  {
   if(arr[i].nodeType == 8)
   {
    comments_found.push(arr[i])
   }else{
    loop(arr[i].childNodes) 
   }
  }
 }
 return comments_found;
}


var comments = find_comments(document)

for(var i=0;i<comments.length;i++){
 var one_comment = comments[i]
 var div = document.createElement("div");
 div.innerHTML = one_comment.data
 for(var j=0;j<div.childNodes.length;j++){
  one_comment.parentNode.insertBefore(div.childNodes[0],one_comment)
 }
}

No comments:

Post a Comment

You can use [CODE][/CODE] to post Javascript code.
You can start a sentence with ">" to make a quotation.