Selecting HTML Elements in JavaScript
Tags: javascript, beginners, webdev
Published: 2024-01-26 15:57:50

Over the past few weeks I've been getting started with web development, and it's already apparent to me that webpages wouldn't be half of what they are without the functionality JavaScript or another programming language provides. One of the main ways to allow a user to affect the DOM through the use of JS is through event listeners, namely the .addEventListener method, which primes an element (or document) to invoke some function in response to a specified event. With this method the user can create elements, remove them, change their attributes or content, the list goes on - but how does one find the element they want to call .addEventListener on? 

##.querySelector and .querySelectorAll

There are a lot of options! The first I'd like to talk about is the .querySelector method, which looks for an element using a string representing CSS selectors and returns the first match as an element object. More specifically, the element is returned as the appropriate subclass of the element object, always HTMLelement in my experience, but also potentially something like SVGelement or MathMLElement. This method is often called on the document node object (as in document.querySelector(selector)) to comb the whole page for the element but can also be called on an element to only pick from that element's children. 

```
<div id=first>
    <div class=child></div>
</div>
<div id=second>
    <div class=child></div>
</div>
```

In this example, document.querySelector('div.child') will return the div inside the div of id "first", while document.querySelector(#second).querySelector(div) and document.querySelector(#second div) will both return the second div that has the class "child." The second could be useful in a case where you already have document.querySelector(#second) stored as a variable. 

It's worth noting that the document and element objects are both subclasses of the node interface, and abstract class that is not used itself but provides a framework that many DOM API objects like document and element are based on. The node interface does not have the querySelector method or any of the other methods discussed below, but its subclasses often do. 

The .querySelectorAll method is called on the same objects and with the same arguments as .querySelector, but it instead returns all of the matching elements as a NodeList. A NodeList is an array-like iterable that contains any sort of node objects, which for .querySelectorAll are elements, often HTMLelements. The method doesn't return an array because the DOM API tries to provide values that can be handled by any programming language, or be "language independent." Invoking document.querySelectorAll('div') for the above HTML would return an NodeList of length 4 containing all of the divs. 

##.getElementsBy

.querySelector, added in 2013, is newer than the following methods and allows the most specificity in one's search. The document object already had the .getElementById, .getElementsByClassName, .getElementsByName, and .getElementsByTagName methods. For all of these, the argument is a string representing the desired value for the attribute in the method name. Elements have all of these methods except the ones for ID and name, ID because there is (or should be) only one element with a specific ID per page so narrowing the search window to an element isn't needed, and name because that attribute is mainly used for matching elements inside a form tag and won't be repeated outside the tag. There is another method that document and element have, .getElementsByTagNameNS, but this deals with namespace, an XML feature not in HTML that I don't and won't bother to understand right now. 

##Which to use?

These methods explain more what they are doing, so if you only need to get elements with a class name instead of, say, getting them by both a class and tag name, they will make your code more readable. .getElementById is useful in this regard. There is another important difference, though: these methods return live objects while querySelectorAll returns a static one. That is to say, if assigns the returned objects of these methods to variables and then adds a new element that fits the search criteria, only one of the variables add the new element:

```
static = document.querySelectorAll('div.child');
live = document.getElementsByClassName('child');
console.log(static); //NodeList [ div.child, div.child ]
console.log(live); //HTMLCollection { 0: div.child, 1: div.child, length: 2 }
const newDiv = document.createElement('div');
newDiv.className = 'child';
document.body.append(newDiv);
console.log(static); // NodeList [ div.child, div.child ]
console.log(live); // HTMLCollection { 0: div.child, 1: div.child, 2: div.child, length: 3 }
```

If there were a change in one of the elements, like adding an id of "new" to the first div.child, that would update in both lists because they both contain references to the DOM elements. Notice .getElementsByClassName returns an HTMLCollection instead of a NodeList; an HTMLCollection is always live and only contains elements (instead of being able to contain any node). A NodeList is usually static, but can be live, as when .getElementsByName returns a live NodeList. NodeLists are also array-like, and need to be accessed by index, whereas HTMLCollections can be accessed by index/key, the id attribute with the namedItem property, and the name attribute with the namedItem property. 

This is all to say that you should use one of the methods other than querySelector if you want to assign it to a variable that will update as new elements that meet the criteria are added. These methods also have the benefit of having more explicit names. But the way querySelector and querySelectorAll use CSS selectors allows for much more precise element selection without resorting to the .children property or others. 

###Works Cited

*JavaScript and HTML DOM*. JavaScript and HTML DOM Reference.  https://www.w3schools.com/jsref/ 

MozDevNet. *Web technology for developers: MDN*. MDN Web Docs. https://developer.mozilla.org/en-US/docs/Web 

Mortensen, P., & Standaert, M. (1957, September 1). *HTML input - name vs. ID*. Stack Overflow. https://stackoverflow.com/questions/7470268/html-input-name-vs-id/7470407#7470407 

Sam, huwiler, & J, T. (1960, February 1). *Javascript why use NodeList instead of using array*. Stack Overflow. https://stackoverflow.com/questions/21768551/javascript-why-use-nodelist-instead-of-using-array 

Semah, B. (2023, December 7). *HTMLCOLLECTION vs nodelist – what’s the difference?* freeCodeCamp.org. https://www.freecodecamp.org/news/dom-manipulation-htmlcollection-vs-nodelist/#differences-between-htmlcollection-and-nodelist