Search code examples
javascripthtmlcssdomtraversal

First Child Last Child Dom traversal not working


I am learning Javascript and encounter a strange problem that I really don't understand. I am following the Book Javascritp and Jquery by Jon Duckett. I am doing the same as described in the book but for some reason it doesn't work. According to the code the first child of ul should get a class of current but it doesn't. Can someone please help and explain whats going wrong with the code. Thanks

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

var firstItem = ul.firstChild;

firstItem.setAttribute('class', 'current');
li {
  list-style: none;
  padding: 10px 15px;
  width: 220px;
  border: 1px solid #eeeeee;
}

.current {
  background: #84ac47;
}

#nav {
  width: 220px;
  border: 1px solid #dedede;
  padding: 10px 15px;
  margin-left: 40px;
  overflow: hidden;
}

#previous {
  float: left;
}

#next {
  float: right;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<ul id='list'>
  <li class='null'>One</li>
  <li id='two'>Two</li>
  <li>Three</li>
  <li>Four</li>
  <li>Five</li>
</ul>
  <div id="nav">
    <button id="previous">Previous</button>
    <button id="next">Next</button>
  </div>
</body>
</html>


Solution

  • You mentioned a book on JavaScript and jQuery so thought I would add an alternative method if you're interested in the jQuery version:

    First

    $("ul#list li:first").addClass("current");
    

    Last

    $("ul#list li:last").addClass("current");