JavaScript Selectors

JerseyFoo

1/g = g-1
Reaction score
40
Might as well write this down somewhere...

Traditional
PHP:
document.getElementById('wrap');
document.getElementsByTagName('div');
document.getElementsByClassName("fancy blue"); // *

/* class method does not work in IE8 or FF2 */

CSS
PHP:
document.querySelector('#wrap > h2 + div');
document.querySelectorAll('p.fancy');

/* Disregard;  IE7  FF3 */

XPath
PHP:
document.evaluate("//div", document, null, 0, null);  

function(){
	var emu = new ActiveXObject("Msxml2.DOMDocument");
	emu.async = false;
	emu.resolveExternals = false;
}
emu.selectNodes('//p')
emu.selectSingleNode('//p')

/* Where emu is a emulated mirror document of the current HTML doc
have fun; http://msdn.microsoft.com/en-us/library/ms757828(v=VS.85).aspx */

The traditional methods are faster for simple selections only.
 

Magentix

if (OP.statement == false) postCount++;
Reaction score
107

JerseyFoo

1/g = g-1
Reaction score
40
It gave the 99% faster thing again, so I tried it for comparing document.getElementById and document['getElementById'] and this test reports a huge difference, meaning it's full of it? On chrome, document.getElementById is 50% slower, on Firefox, document['getElementById'] is 66% slower.

Regardless something is definitely going on with that test and document.getElementById.
 

Magentix

if (OP.statement == false) postCount++;
Reaction score
107
It gave the 99% faster thing again, so I tried it for comparing document.getElementById and document['getElementById'] and this test reports a huge difference, meaning it's full of it? On chrome, document.getElementById is 50% slower, on Firefox, document['getElementById'] is 66% slower.

Regardless something is definitely going on with that test and document.getElementById.

document.getElementById is a simple call to a commonly used method, whereas document[someVar] needs to evaluate someVar first, then see if it's a property and then use that property.
Also grab() is faster than document.getElementByid because you made it a reference value of an object, whereas document.getElementById requires a property lookup (which is, in this case, marginally slower)


But again: my complaint isn't about speed, it's that you don't take live versus static into account
(and that you don't compare XPath versus document.getElementById, even though your test name suggests you do)
 
General chit-chat
Help Users
  • No one is chatting at the moment.

      The Helper Discord

      Staff online

      Members online

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top