Home > database >  How to edit List Item Elements using javascript
How to edit List Item Elements using javascript

Time:12-08

I'm trying to change "Milk" to oat milk by using some javascript that will be run through the google dev console. The HTML looks like;

<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="style.css" />
  </head>

  <body>
    <div id="groceries-section">
      <h1>Our Shopping List</h1>
      <ul id="grocery-list">
        <li>Milk</li>
      </ul>
    </div>
    <script src="main.js"></script>
  </body>
</html>

I'm able to get the id using;

document.getElementById("grocery-list")

but I am unsure how to access the "Milk" li. I'm new to this so any help is appreciated.

CodePudding user response:

You can use querySelector to get the first li element inside the ul element with the id grocery-list.

document.getElementById("grocery-list").querySelector("li").innerHTML = "Oat Milk";

CodePudding user response:

If you want to only change the first li element from ul:

document.querySelector('ul li').innerText = 'Aloha'

If you have multiple <li>Whatever</li> you could do the following:

document.querySelectorAll('ul li').forEach(el=>{
    el.innerText = 'Milka'
})

If you want to select only the li with Milk value, from multiple elements, you could do:

document.querySelectorAll('ul li').forEach(el=>{
    if(el.innerText == 'Milk'){
        el.innerText = 'Oat Milk'
    }
})
  • Related