JavaScript DOM Scripting By Example Editing and Filtering Names Fix DOM Manipulation Code

Michael Williams
PRO
Michael Williams
Pro Student 8,057 Points

Logically, wouldn't this not work?

Correct answer aside, i == index, wouldn't this technically not run properly if the users are entering 1-3 in the input field, but javascript is starting from 0?

app.js
const laws = document.getElementsByTagName('li');
const indexText = document.getElementById('boldIndex');
const button = document.getElementById('embolden');

button.addEventListener('click', (e) => {
    const index = parseInt(indexText.value, 10);

    for (let i = 0; i < laws.length; i += 1) {
       let law = laws[i];

       // replace 'false' with a correct test condition on the line below
       if (i = index) {

           law.style.fontWeight = 'bold';
       } else {
           law.style.fontWeight = 'normal';
       }
    }
});
index.html
<!DOCTYPE html>
<html>
<head>
  <title>Newton's Laws</title>
</head>
<body>
  <h1>Newton's Laws of Motion</h1>
  <ul>
    <li>An object in motion tends to stay in motion, unless acted on by an outside force.</li>
    <li>Acceleration is dependent on the forces acting upon an object and the mass of the object.</li>
    <li>For every action, there is an equal and opposite reaction.</li>
  </ul>
  <input type="text" id="boldIndex">
  <button id="embolden">Embolden</button>
  <script src="app.js"></script>
</body>
</html>

1 Answer

Ajay Prasannan
Ajay Prasannan
13,908 Points

That's very true; if the user is unaware of zero-indexing, they will run into this problem. Perhaps the addition of some copy would explain that to them, plus some feedback if they enter something out of array bounds? Or, maybe an offset could be set up to ensure users can enter 1-3?