JavaScript JavaScript and the DOM Getting a Handle on the DOM Using CSS Queries to Select Page Elements

Alex Herrera
PRO
Alex Herrera
Pro Student 6,392 Points

Why would you not ALWAYS use this selector?

It seems that the querySelector selectors are able to to do what everything the getElement(s) selectors are able to do.

Why would you not just use querySelector all the time...?

3 Answers

Steven Parker
Steven Parker
179,663 Points

Why carry only one tool when your toolbox can hold several?

Sure, querySelector is the "swiss army knife" of selection methods, but in some situations the other methods might be more efficient and/or more clearly convey the program intention to someone reading and maintaining the code.

Agreed. I think it's just easier/better readability.

Michael Brown
Michael Brown
12,406 Points

Which is most commonly used or best practice? I'm more familiar with "getElement(s)" by way of Android development, but it seems like querySelector is a beefier option.

Steven Parker
Steven Parker
179,663 Points

I'm not sure that choice of method would fall into the realm of "best practice" as long as the intent was clear. Personally, I would use querySelector anytime a combined selector is needed (rather than chaining the other methods), but if I just wanted an element that has an ID, I'd use getElementById.

ian izaguirre
ian izaguirre
3,220 Points

A few more reasons for why you would not always use querySelector:

1) Project Support. getElementById is supported by more older browsers. So if you are working with older code that needs wider browser support, then you would use that. An example, getElementById works with IE5.5 but querySelector is supported starting with IE8.

2) Performance. An example, getElementByClassName and getElementByTagName works faster than querySelectorAll.

3) getElementById is more specific in certain situations then querySelector, since querySelector ONLY returns the FIRST matching element.

Steven Parker
Steven Parker
179,663 Points

I'm not sure 2 is true for all browsers. I think some use internal optimizations so the performance is about the same.

And regarding 3, getElementById ONLY returns one element (if any) in all situations, so in that aspect it is exactly the same as when using querySelector on ID's. Element ID's are required to be unique.

ian izaguirre
ian izaguirre
3,220 Points

@Steven Parker

Your right :)