zain
zain

Reputation: 444

Difference between using document.querySelector('#id') and document.getElementById('id')

I am a beginner in javascript and I have seen many people using document.querySelector('#id') and some people using document.getElementById('id') for grabbing the html element with the id. Please answer weather these are same or we have to use them differently.

Upvotes: 2

Views: 9010

Answers (2)

hassan
hassan

Reputation: 1

I think a significant difference between them is; getElementById effect both on element and content of this,but quarySelector only effect element.

Upvotes: -2

Soren
Soren

Reputation: 21

Quite significant difference is that .getElementById is only applicable on document level while .querySelector can be applied on element level. I.e querySelector allows you to control where to start traversing while getElementById will always traverse from the document root. This means that that querySelector does not require an id to unique within the whole document but only to be unique within a node.

Upvotes: 1

Related Questions