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

Viewed 1662

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.

1 Answers

When you use getElementById to assign a variable, you don't have to declare that you're looking for an id in the document because it's already in the method's name and functionality. When you perform the same thing with querySelector, though, you're using CSS selectors, so you'll need to add the # to indicate that you're looking for an id, and that's the key difference.

const container = document.getElementById("container")

vs

const banner = document.querySelector("#banner")

Initially both do the same thing.

Related