Home > OS >  Is getElementById or getElementsByClassName[0] faster?
Is getElementById or getElementsByClassName[0] faster?

Time:03-27

Is it faster to use getElementById

document.getElementById('foo').style.visibility = 'visible';

or getElementByClassName[0]

document.getElementsByClassName('foo')[0].style.visibility = 'visible';

I have read that too many IDs can hamper performance, which is why I am trying to shy away from IDs. But if it is faster to use an ID for a quick JavaScript lookup, I will gladly do so.

CodePudding user response:

getElementById would be the fastest method, since it's simple table lookup.

getElementsByClassName the same as querySelector almost twice as slow.

For best performance use ids for javascript and classes for CSS.

  • Related