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 Changing Classes

Brian Bartlett
Brian Bartlett
20,278 Points

Why doesn't this work for task2? anchor.classList.toggle("live");

The error message says that I am not using the toggle() method. I'm not sure what the problem is.

app.js
var anchor = document.querySelector("a");

//Add the class to the classList "selected"

anchor.className = "selected";

//Toggle the class "live"

anchor.classList.toggle("live");
index.html
<!DOCTYPE html>
<html>
<body>

  <a href="#">Home</a>

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

</body>
</html>

2 Answers

Merritt Lawrenson
Merritt Lawrenson
13,477 Points

I checked and 'anchor.className = "selected";' does pass the first part of the challenge for some reason, but it's not the method the challenge wants, and part 2 won't pass if you use it.

Part one wants you to use the 'classList' property to add the class "selected". To add a class like this, you'll want to use the 'classList.add()' method to add that class to the list of classes. That'll make the code challenge complete sucessfully.

var anchor = document.querySelector("a");

//Add the class to the classList "selected"

anchor.classList.add("selected");  

//Toggle the class "live"

anchor.classList.toggle("live");
Erik McClintock
Erik McClintock
45,783 Points

Brian,

Your code for the toggle method is correct, but you need to make sure you're leaving the the code from the previous task in the challenge (the "anchor.classList.add('selected')" code).

You want this as your final code:

var anchor = document.querySelector("a");

//Add the class to the classList "selected"

anchor.classList.add('selected');

//Toggle the class "live"

anchor.classList.toggle('live');

Erik