最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Performance of getElementById vs. getElementsByClassName vs. querySelector - Stack Overflow

programmeradmin5浏览0评论

I was reading about dom manipulation topic in dev.mozilla and I came across with a statement that suggest us to use querySelector for element selection:

Note that, as with many things in JavaScript, there are many ways to select an element and store a reference to it in a variable. Document.querySelector() is the remended modern approach...

However, when I made a test I realized getElementsByClassName() is by far the best method for element selection. How e it can be faster than getElementById() ? And why mozilla dev guide still reends using querySelector() even though it's the slowest one amongs them ?

I was reading about dom manipulation topic in dev.mozilla and I came across with a statement that suggest us to use querySelector for element selection:

Note that, as with many things in JavaScript, there are many ways to select an element and store a reference to it in a variable. Document.querySelector() is the remended modern approach...

However, when I made a test I realized getElementsByClassName() is by far the best method for element selection. How e it can be faster than getElementById() ? And why mozilla dev guide still reends using querySelector() even though it's the slowest one amongs them ?

Share Improve this question asked Jul 23, 2019 at 7:50 brainoverflow98brainoverflow98 1,2782 gold badges13 silver badges30 bronze badges 9
  • 8 Faster than getElementById oO? You did something wrong. getElementById is just a table lookup and is the definitive winner. However, why do you bother? Do you really have a bottleneck at DOM selection? – Kaiido Commented Jul 23, 2019 at 8:02
  • 2 Note getElementsByClassName returns a live node list, whereas querySelector(All) and getElementById don't. – Andy Commented Jul 23, 2019 at 8:05
  • getElementsByClassName will return the same Javascript object (collection) when invoked again with the same argument. Don't know if the jsperf test takes that into account or not – CertainPerformance Commented Jul 23, 2019 at 8:06
  • 1 @brainoverflow98 The answer is that it doesn't really matter. querySelector is preferred because of its simplicity and because it doesn't return a live collection – Bergi Commented Jul 23, 2019 at 12:14
  • 1 getElementById is faster (but only noticeable in performance tests) because since very early Internet-Explorer days the Browser creates global variables for all ID values. So as Kaiido says, in the first ment, getElementById is just a table lookup. All Browser vendors copied this behavior, many moons ago, because once Microsoft owned 90% of the Browser market, and all Browsers had to support Web applications written on top of this (Microsoft) ID behavior. Today, all Browsers but FireFox still create a totally valid 'IDname' global Array of IDs for duplicates IDs. – Danny '365CSI' Engelman Commented Sep 26, 2020 at 10:59
 |  Show 4 more ments

1 Answer 1

Reset to default 13

The main advantage of document.querySelector is the ease of use with more plex CSS queries.

const loginFields = document.querySelector("form.login input");
if (loginFields.some((field) => field.value.trim() === "") {
    alert("Please fill in all fields");
}

The alternative would be to use document.getElementsByClassName and Element.getElementsByTagName.

const loginFields = document.getElementsByClassName(".login")[0]
    .getElementsByTagName("input");
if (loginFields.some((field) => field.value.trim() === "") {
    alert("Please fill in all fields");
}

As you may have noticed, you'll often store the return result into a constant/variable. You're (usually) not supposed to call this in a for/while loop.


Regarding the (archived) performance test, it looks quite unfair because all tests except the class test will run two queries.


So I decided to do some more testing. In the HTML of that page, I added the id "codeOne" to the first element with the class "code".

Then I ran four tests.

Out of these test results, I can conclude that getElementById using id (691ms) is the clear winner with querySelector using id (749ms) ing in second. This is because ids are easy to look up as browsers copied this feature from Internet Explorer, which was the most dominant browser in the past. You can even use ids as if they are variables.

Please don't do that because it's less readable. It's also not faster.

When we take a look at the tests using class, we can see a massive performance difference between getElementsByClassName (778ms) and querySelector (1460ms). This is because the former will only look for classNames while the latter will do some extra checks because it can use a plex query like '#id.class[attr="value"]' or "form > input".


The final conclusion is that you can use document.querySelector for one element and document.querySelectorAll for multiple elements just for simplicity as any CSS query will work. The functions getElementById and getElementsByClassName (as well as getElementsByTagName, not included) should always be faster in theory but in practice this shouldn't affect the performance of your website. You (probably) won't call these functions in a loop so you can just store the result in a variable.

发布评论

评论列表(0)

  1. 暂无评论