[SOLVED] Is getElementById or getElementsByClassName[0] faster?


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.


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.

Answered By – vanowm

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *