What is the difference between "document.getElementById" and "document.querySelector"?

From this lesson, what is the difference between document.getElementById() and document.querySelector()?

In the Hint section accompanying the exercise, the following lines of code was used as an example.

let paragraph = document.querySelector('p');

However, I used the following lines of code in solving the exercise and it worked.

let todo = document.getElementById("oaxaca");

Can they be used interchangeably?

Same question is applicable for document.body.removeChild(paragraph); and document.getElementById("more-destinations").removeChild(todo);

Is there a difference between the both of them or can they be used interchangeably?

I believe that document.getElementById('idName') is only useful for referencing selectors by their id.
But, document.querySelector('selectorName') can be used to reference elements by id or class. So, it has more flexibility.

With the second question, they are essentially the same since you are just defining the same path in two ways. If you know that the child ‘paragraph’ is located under the body node and not further down the tree,then the first example you gave works. If you aren’t sure where in the hierarchy that element exists, but you know it has an id=‘more-destinations’, then this gets you there quickly.

1 Like

It is actually even more flexible than that!
document.querySelector() can be used with any valid CSS selector:

const a = document.querySelector("div p.top:first-child:")

This will select elements that are the first child of a <p class="top"> that is nested inside a <div>

1 Like

Thanks for that. It could come in handy on more complex builds.

1 Like