Search code examples
javascriptapidomconsoleinnertext

Change innerText of HTML list items from console with JavaScript


I am new to programming and I have been looking for solutions, but what I find are more complciated solutions than it should be and I am being asked. I have this HTML

<!DOCTYPE html>
<html lang="en">
 <head>
  <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
  <meta content="utf-8" http-equiv="encoding">
 </head>
 <body>
  <h3>Pizza toppings:</h3>
  <ul id="ingredients">
   <li>Batsilica</li>
   <li>Tomtato</li>
   <li>Morezarella</li>
   <li>Hams</li>
  </ul>
 </body>
</html>

So I have to change the ingredients with the console. I wrote this so I get printed the list:

let toppings = document.querySelectorAll('#pizza-toppings li');
for (let i = 0; i < ingredients.length; i++) {
    console.log(ingredients[i].innerText);
}

I dont know how to modify those items of the list one by one. It shouldnt be any replaceChild nor change the list completely, but selecting them and "modifying them". maybe I get the children list of the element with qSelector but still dont know how to correct the spelling of those. It is not like I can right click in the printed list and edit it.

Help? Thanks


Solution

  • Infact we use # to select an id, so you need to put your list's id which is ingredients. And your array of matching items is called toppings, so you need to set your loop limit to toppings.length. Although i would recommend using map instead of for loop

    let toppings = document.querySelectorAll('#ingredients li');
    for (let i = 0; i < toppings.length; i++) {
        console.log(toppings[i].innerText);
    }
    

    This should display all of your items on the console. But if you want to edit item, for example you want to change "Tomtato" into "Meat" you have to do

    toppings[1].innerText="Meat"