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

Michael Williams
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?

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) {

  = 'bold';
       } else {
  = 'normal';
<!DOCTYPE html>
  <title>Newton's Laws</title>
  <h1>Newton's Laws of Motion</h1>
    <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>
  <input type="text" id="boldIndex">
  <button id="embolden">Embolden</button>
  <script src="app.js"></script>

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?