How to grab HTML Elements in Javascript

Iuri Seara
2 min readSep 9, 2020

--

When it comes to using Javascript to manipulate the DOM, often you find yourself wanting to manipulate HTML Elements. But to do so you have to find the elements first! In this blog, you will learn how to do so.

Find Element By Id

The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they’re a useful way to get access to a specific element quickly.

Find Element By Name

The getElementsByName() method returns a collection of all elements in the document with the specified name (the value of the name attribute), as an HTMLCollection object.

Find Element By Tag Name

The getElementsByTagName() method returns a live HTMLCollection of elements with the given tag name. All descendants of the specified element are searched, but not the element itself. The returned list is live, which means it updates itself with the DOM tree automatically. Therefore, there is no need to call Element.getElementsByTagName() with the same element and arguments repeatedly if the DOM changes in between calls.

Find Element By Class Name

The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class name(s). When called on the document object, the complete document is searched, including the root node. You may also call getElementsByClassName() on any element; it will return only elements that are descendants of the specified root element with the given class name(s).

Find Element By CSS Selector

The Document method querySelector() returns the first element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned. querySelector() is more useful when you want to use more complex selectors.

It is important to note that querySelector() returns the first element within the document that matches the specified selector. If you wanted to select all of the elements that match the specified selector you would use querySelectorAll()

--

--

Iuri Seara

Software Engineering Student at Flatiron School New York City