Help me different between querySelector and getElementById in HTML | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Help me different between querySelector and getElementById in HTML

8th May 2018, 6:02 PM
Trung Hieu Tran
Trung Hieu Tran - avatar
2 Answers
+ 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
8th May 2018, 6:54 PM
Burey
Burey - avatar
+ 2
<div id="tube" ></div> tube=document.getElementById("tube"); tube=document.querySelector("#tube"); 1st yanks out elements with id 2nd uses css selectors
8th May 2018, 7:07 PM
᠌᠌Brains[Abidemi]
᠌᠌Brains[Abidemi] - avatar