Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Interactive Web Pages with JavaScript Traversing and Manipulating the DOM with JavaScript Traversing Elements

Richard Brinkley
Richard Brinkley
4,807 Points

Why use querySelector() to get the "a" element? Wouldn't getElementsByTagName() be a better choice?

In Challenge Task 2 of 2 for Traversing Elements, the question reads:

"On line 14 of the app.js, we want to get the anchor (the a element) from inside the listItem. Use a method to traverse and select the anchor."

The code on line 14 reads: var anchor = listItem;

Given that the anchor tag is an element, and the task was to "get" the anchor element, I used getElementsByTagName(), but the Challenge Task failed. However, I tested this method in the console and it works.


//Select the naviagation
var navigation = document.getElementById("navigation");

//Select all listItems from the navigation
var listItems = navigation.children;

//When a navigation link is pressed
var linkListener = function() {
  console.log("Listener is clicked!");

var bindEventsToLinks = function(listItem) {
  //Select the anchor
  var anchor = listItem.querySelector("a");
  //Bind the linkListener to the anchor element (a) 
  anchor.onclick = linkListener;

for(var i = 0; i < listItems.length ; i++) {
<!DOCTYPE html>

<ul id="navigation">
    <a href="#home">Home</a>
    <a href="#about">About</a>
    <a href="#contact">Contact</a>

<p>A few of my favourite things:</p>
    Rain drops on roses
    Whiskers on kittens
    Brown paper packages wrapped up with string

<script src="app.js"></script>

2 Answers

Hi Richard,

The code that follows this DOM lookup assumes that you will be working with a single element. getElementsByTagName() returns a collection of elements (HTMLCollection) instead of a single element. Note the plurality of "Elements" in the function name. querySelector() will return the first element that matches the given query, which means the .onclick assignment that happens next will work just fine without having to specify an array index.

Karina Machado
Karina Machado
5,999 Points

Sean good example , I get it better now.