AFAIKS, that's exactly what your javascript snippet also does, isn't it?

Yes.
 
I run a very recent bzr emacs, so maybe the problem is already solved in
between 24.1 and now...

I run the trunk version too.

Fabrice