querySelector vs getElementById

Vincentservio
1 min readMar 17, 2021

--

Learning Javascript comes with tons of repetitive coding. From functions, to using methods, understanding what you are trying to control from your web page is important. The only way to properly manipulate a section of your web page is by using the proper method. Using the wrong method can result in unwanted errors or even stop objects from appearing on the page .

document.getElementById("example")

Get element by ID is a method that returns an element with an ID matching the text given (“example”). This method will search through the document and locate an element with an id of “example”. The HTML for this element would look something like this

<div id="example"></div>

document.querySelector(“form”)

Query selector can be used the same way, however how they work slightly different. Query selector returns the first element matching the specified selector(“form”). This is helpful when you would like to manipulate or read by a CSS object. You can also have multiple queries as long as they are separated by spaces. document.querySelector(“form h1”) . The HTML syntax would look something like this

<form>
Name: <input type="text" name="name">
<input type="submit" value="Submit">
</form>

Query selector can be used to display, read or manipulate the values of this form.

Thanks for reading!!!!

--

--

No responses yet