javascriptdomgetelementbyidqueryselector

What's the difference between querySelector() and getElementBy[Id/ClassName/TagName]?


I don't get the difference between using querySelector() and, let's say, getElementById(). I understand that querySelector retrieves an element by using any selector, which makes it more versatile.

Are there any more differences? When should I use getElementById instead of querySelector?


Solution

  • According to this article:

    getElementById() can run about 15 million operations a second, compared to just 7 million per second for querySelector() in the latest version of Chrome.

    So, if that amount of performance is important to you, it makes sense to do that. Otherwise, no, there is no difference other than the aforementioned flexibility.