Welcome to our free JavaScript tutorial. This tutorial is based on Webucator's Introduction to JavaScript Training course.
beatle.setAttribute("id", prop);
to set an id
for each list item as we iterate over the array to build our ordered list.<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>JavaScript Loops</title> <script> var index; var beatles = []; beatles["Guitar1"] = "John"; beatles["Bass"] = "Paul"; beatles["Guitar2"] = "George"; beatles["Drums"] = "Ringo"; window.onload = function() { for (var prop in beatles) { var beatle = document.createElement("li"); beatle.setAttribute("id", prop); var textnode = document.createTextNode(prop + " : " + beatles[prop]); beatle.appendChild(textnode); document.getElementById("beatles").appendChild(beatle); } console.log(beatles); document.getElementById("redgeorge").addEventListener("click", function() { document.getElementById("Guitar2").style.color='red'; return false; }); } </script> </head> <body> <h1>JavaScript Debugging</h1> <ol id="beatles"> </ol> <div class="buttons"> <ul> <li><a href="#" id="redgeorge">Set George Red</a></li> </ul> </div> </body> </html>
The issue here is that the event handler for a user click on the "Set George Red" link references the wrong id
: instead of setting the element with id
Guitar2
to be red, we (wrongly) set the element with id
Guitar1
to be red.
We can use the Chrome DevTools in a couple of ways to help us in our task of finding the bug in the code. First, we might have used the "Elements" console to quickly scan the id
s of the list items:
and seeing that the "George" list item has id
Guitar2
. We might also have used console.log(beatles)
to list the elements of our array, to compare the indices of our array against the id
s we see in the "Elements" panel:
Of course, we don't really need the DevTools here - we could have gone through the source of our code, rather than reviewing it in the browser and inspecting via DevTools - to find and fix the bug. But because DevTools makes it so easy to inspect DOM elements and view collections like arrays in the console, DevTools is often the preferred method of debugging, especially as your JavaScript code gets more complicated.
This tutorial is based on Webucator's Introduction to JavaScript Training Course. We also offer many other JavaScript Training courses. Sign up today to get help from a live instructor.