Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does {x:expression(...)} do? [duplicate]

I came across this polyfill of querySelectorAll for IE7:

https://gist.github.com/connrs/2724353

I had thought that I am Okayish in JavaScript, but I have never seen anything like the quoted part in line 9 of the polyfill:

{x:expression(document.__qsaels.push(this))}

Apparently, it is a JavaScript object with key x and value expression(document.__qsaels.push(this)), but other than this much I know, it is mysterious to me. What does this expression function do? I was not able to find anything close via google.

like image 699
Stack0verflow Avatar asked Dec 19 '22 02:12

Stack0verflow


1 Answers

You are looking at a generated CSS rule. This is not a JavaScript object, but a CSS declaration block.

The line

styleTag.styleSheet.cssText = selector + "{x:expression(document.__qsaels.push(this))}";

concatenates a CSS selector with a declaration block into a string of CSS. The declaration block contains a dummy CSS property called x with a value of expression(document.__qsaels.push(this)).

What expression() is, is a non-standard feature of old versions of IE that allows the author to execute arbitrary JavaScript directly and obtain a value for use within CSS. So while the entire string is a CSS declaration block, document.__qsaels.push(this) is in fact a JavaScript expression.

What this expression does, is push any element matching the CSS selector into the __qsaels array so that the polyfill can return it as the set of elements matched by the selector.1 This, in essence, is how the polyfill works.

As a concrete example, calling the polyfilled document.querySelectorAll(".foo") causes IE7 to append the following CSS to the document stylesheet:

.foo{x:expression(document.__qsaels.push(this))}

With some indentation and newlines so it resembles conventional CSS:

.foo {
  x: expression(document.__qsaels.push(this))
}

Here you can see that this CSS rule will apply to any element that matches .foo, causing each element to be added to __qsaels before it is returned.


1For whatever reason, IE seems happy to execute expression() statements even on unknown properties (AFAIK there isn't such a property called x even on IE7, but what do I know?).

like image 96
BoltClock Avatar answered Dec 24 '22 00:12

BoltClock