getElementById("ID") allows you to select any element only based on its id, getElementByClassName("class") allows you to select any element only based on its class name and the querySelector("css-selectors") allows you to select any element based on CSS selector pattern. It means that querySelector can be used in place of getElementById and getElementByClassName so that the code looks more uniform and readable. In addition, querySelector can be more useful if we need to perform more complex selections on HTML which we often do.
Keeping all these benefits of querySelector over getElementById and getElementByClassName, if we look at the performance only then we see that querySelector is slower than the other. To experiment with this following is the code:
See the Pen
DOM selector functions performace by Vidyasheela (@_vidyasheela)
on CodePen.
If you run this code you will find that querySelector is slower than getElementById and getElementByClassName. Among getElementbyId and getElementByClassName, getElementById is slightly faster.
These are the experiment results with 10000000 iterations
You can see that the execution time is in ms even for 10000000 iterations, which means that all of these selector functions are fast. so in my opinion, you should use querySelector instead of getElementById or getElementByClassName, but not because of performance. The performance increase is negligible and will not matter in any real-world application. The real reason is a single standardized way of making element selections whether by type, id, class, etc
Post a Comment
No Comments