0

I am. A beginner of JavaScript and am confused that what is the difference between document.querySelector('#button') and document.getElementById('button')?

For example,

function myFunction() {
  document.querySelector("#demo").innerHTML = "Hello World!";
}

And

function myFunction() {
  document.getElementById("demo").innerHTML = "Hello World!";
}

Give the same result. Then what is the difference between them?

I know that querySelector() returns the first element matching, but IDs are already unique...

SK-the-Learner
  • 523
  • 5
  • 18

2 Answers2

0

Query selector will select the first element in the Dom which matches the query, it can be an ID, tag, class etc. getElementById will select the ID

lhuf
  • 42
  • 9
0

They pretty much do the same thing. It's down to opinion and none is better than the other.

Tom Roman
  • 125
  • 1
  • 8
  • Then why is there an existence of both of them.. – SK-the-Learner Mar 09 '21 at 11:53
  • Well, let me rephrase. querySelector returns a HTMLElement and getElementById returns just an Element. Read more here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement https://developer.mozilla.org/en-US/docs/Web/API/Element In most use cases, this is not an issue, but sometimes you may want one over the other – Tom Roman Mar 09 '21 at 11:58