0

I'm learning DOM and I'm trying to select an li within a div, where the div has an ID of 'essentials' I want to target all li within that div and change the background color. I was able to change the background color of the div itself, but can't seem to select just the li. Here's my code:

HTML

    <ul>
      <li>milk</li>
      <li class="selected">honey</li>
      <li>water</li>
      <li>wine</li>
      <li>beer</li>
    </ul>
  </div>

Javascript

document.getElementById('essentials').style.backgroundColor = 'yellow';
KevMcCall
  • 25
  • 1
  • 10

2 Answers2

2

Modern browsers provide you with two fantastic APIs for targeting DOM elements:

document.querySelector (get one element) and document.querySelectorAll (get more than one element)

These two methods allow you to target DOM elements using CSS selectors. For example:

With the following HTML:

<div id="essentials">
  <ul>
    <li>milk</li>
    <li class="selected">honey</li>
    <li>water</li>
    <li>wine</li>
    <li>beer</li>
  </ul>
</div>

You can target the li tags you want with this JavaScript:

var myLiTags = document.querySelectorAll('#essentials li'):

Now, to style your targeted li tags, you can do this:

myLiTags.forEach(function(el) {
  el.style.backgroundColor = 'yellow';
});

Of course, if you don't need to do this with JavaScript, styling elements is what CSS was made for:

<style>
  #essentials li {
    background-color: yellow;
  }
</style>

Putting this code in your HTML document will work as well as the JavaScript code above, but is actually the best-practices way of styling DOM elements.


If you're new to CSS Selectors, here's a tutorial

bmdev
  • 386
  • 1
  • 7
  • Actually I've already gone through HTML, CSS, and JS courses. We are now learning DOM and this is the way we have to do it. I understand that this can easily be accomplished through CSS. Thank you for your help! – KevMcCall Jan 14 '21 at 22:14
0

Use querySelectorAll

    var q = document.querySelectorAll('#essentials li');
    console.log('q' + q.length);
    q.forEach(function(elem) {
      elem.style.backgroundColor = 'yellow';
    });
<body>
<div id="essentials">
<ul>
<li>a
<li>b
<li>c
</ul>
</div>
</body>
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80