0
Help me different between querySelector and getElementById in HTML
2 Réponses
+ 8
actually Trevor Hodges
querySelector uses css selectors to locate the first element which satisfies the selector (and can be used with vanilla js)
for example:
document.querySelector(".my-class > #my-div")
https://www.w3schools.com/jsref/met_document_queryselector.asp
-------------------------
getElementById simply take in the id name (plain string) without any css selectors:
for example:
document.getElementById("my-div")
https://www.w3schools.com/jsref/met_document_getelementbyid.asp
-------------------------
same logic also applies for getElementsByClassName
only the class name is passed and a collection is returned (even if there is only one element with the fiven class name)
https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
+ 2
<div id="tube" ></div>
tube=document.getElementById("tube");
tube=document.querySelector("#tube");
1st yanks out elements with id
2nd uses css selectors