I have seen a snippet like this for detecting IE in JavaScript using conditional comments.
var ie = (function(){
var undef, v = 3, div = document.createElement('div');
// the while loop is used without an associated block: {}
// so, only the condition within the () is executed.
// semicolons arent allowed within the condition,
// so a comma is used to stand in for one
// basically allowing the two separate statements
// to be evaluated sequentially.
while (
div.innerHTML = '<!--[if gt IE '+(++v)+']><i></i><![endif]-->',
div.getElementsByTagName('i')[0]
);
// each time it's evaluated, v gets incremented and
// tossed into the DOM as a conditional comment
// the i element is then a child of the div.
// the return value of the getEBTN call is used as
// the final condition expression
// if there is an i element (the IE conditional
// succeeded), then getEBTN's return is truthy
// and the loop continues until there is no
// more i elements.
// In other words: ** MAGIC**
return v > 4 ? v : undef;
}());
The above given is the documented (and slightly improved) version by Paul Irish on a snippet by James Padolsey. I am posting the commented version to let you know that I might need a simpler explanation if anybody may.
I would really like to know what happens inside the while loop. I don’t understand that.
(Assuming I haven’t bungled this up horribly) the
whileloop is equivalent to the following:Here’s what MDC says about
while:We can find out exactly what an expression is in JavaScript from MDC:
If you’re feeling brave, you can also check out the ECMA-262 language specification, specifically the following sections:
,)whileStatementSorry I can’t provide direct links as it’s all inside of a PDF.