"Swift Basics (retired)" was retired on May 31, 2020.

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

jQuery First and Last Child Question

Hello everyone, I am trouble understand why my Javascript script is not working and rendering correctly I was wondering if anyone can check it out. I am trying to change the class attributes of the li elements in the ul element. For me, the classes are not changing. I have a CodePen if anyone would like to check it out. http://codepen.io/Trejo/pen/vOjZdP

<ul>
        <li id="one" class="hot"><em>fresh</em> figs</li>
        <li id="two" class="hot">pine nuts</li>
        <li id="three" class="hot">honey</li>
        <li id="four">balsamic vinegar</li>
</ul>
.hot {
background: red;
}

.cool{
background: blue;
}
// Select the starting point and find its children.
var startItem = document.getElementsByTagName('ul');
var firstItem = startItem.firstChild;
var lastItem = startItem.lastChild;

// Change the values of the children's class attributes.
firstItem.className = 'complete';
lastItem.className = 'cool';

2 Answers

I'm going to be perfectly honest, I haven't been able to figure out a working JS version in the past twenty minutes. Something about the way it's selecting things doesn't seem to be working. The console.log messages I set up kept coming back undefined.

The following JQuery works for me, though.

$(document).ready(function() {

  $('ul li:last').removeClass('hot');
  $('ul li:last').addClass('cool');

  $('ul li:first').removeClass('hot');
  $('ul li:first').addClass('complete');

});

Okay! I've got a JS version, with some caveats. Whitespace is not your friend here. For this to work you need to have no whitespace in between the ul and li tags. This was causing all kinds of issues, probably yours included.

You can read a bit more about the whitespace issues using .firstChild and .lastChild on the MDN page.

var startItem = document.getElementsByTagName('ul')[0];

var firstItem = startItem.firstChild;
var lastItem = startItem.lastChild;

firstItem.className = 'complete';
lastItem.className = 'cool';
<ul><li id="one" class="hot"><em>fresh</em> figs</li>
    <li id="two" class="hot">pine nuts</li>
    <li id="three" class="hot">honey</li>
    <li id="four">balsamic vinegar</li></ul>