0

I am new to JavaScript, and to stack overflow, so excuse me if I am being oblivious. I was trying to built a progress bar for several classes with the same class name:

<div class="skill">
                <h4>Javascript</h4>
                <div class="progress-bar" data-label="Loading..." style="--width: 10">
                </div>
              </div>
              <div class="skill">
                <h4>Wordpress</h4>
                <div class="progress-bar" data-label="Loading..." style="--width: 10">
              </div>
              <div class="skill">
                <h4>Java</h4>
                <div class="progress-bar" data-label="Loading..." style="--width: 10">
                </div>
              </div>
              <div class="skill">
                <h4>Bootstrap</h4>
                <div class="progress-bar" data-label="Loading..." style="--width: 10">
                </div>

but the JavaScript code:

 const progressBar = document.getElementsByClassName
    ('progress-bar')[0]
    setInterval(() => {
      const computedStyle = getComputedStyle(progressBar)
      const width = parseFloat(computedStyle.getPropertyValue
        ('--width')) || 0
      progressBar.style.setProperty('--width', width + .1)
    },5)

was applied only to the first class:

<h4>Javascript</h4>
                <div class="progress-bar" data-label="Loading..." style="--width: 10">
                </div>

Where did I go wrong? Thank you for your time.

alison
  • 13
  • 3
  • 1
    You went wrong by not paying attention to the docs and [examples](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName#examples) - specifically the 4th one down. Using array syntax `[0]` will limit the results to the first one. You will need to get them all and then iterate over them. – Randy Casburn Apr 04 '21 at 21:36
  • @charlietfl, I don't think that dupe reference is applicable here, as the OP has accessed element zero of the collection, so they are aware of the fact that it is an array-like value. – trincot Apr 04 '21 at 21:46
  • @trincot *"aware of"* .. perhaps not. Just figured the details on how to iterate are there and OP would see the path to follow. Along with MDN exaample of `[0]` – charlietfl Apr 04 '21 at 21:49

1 Answers1

0
('progress-bar')[0]

this will select the first item that it finds.. try this..

const pb = document.getElementsByClassName('progress-bar');
for(var i; i<pb.length ; i++)
{
   pb[i].//your codes for each item
}