Home > Software design >  JavaScript getElementByClassName setAttribute not working
JavaScript getElementByClassName setAttribute not working

Time:11-13

I would like to iterate over a html collection return by the getElementByClassName function. I would like to user the setAttribute method to add "table-info" to the class attribute of the elements in the collection.

My problem is that not all elements are modified, to be specific only the 1st element of the collection does not have it's class changed. It is especially confusing for me that if I hardcode the for loop, the result is still not achieved. enter image description here


<head>

    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, width=device-width">
    <link crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" rel="stylesheet">
    <script crossorigin="anonymous" src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg OMhuP IlRH9sENBO0LRn5q 8nbTov4 1p"></script>

    <link href="/static/favicon.ico" rel="icon">

    <link href="/static/styles.css" rel="stylesheet">

    <title>Country comparison: {% block title %}{% endblock %}</title>

</head>
<body>
    <div>
        <table >
            <tbody>
                <thead>
                    <th>Country</th>
                    <th>Currency</th>
                    <th>GDP</th>
                    <th >Unenployment Rate</th>
                    <th >Inflation Rate</th>
                    <th >Interest Rate</th>
                    <th>Balance of Trade</th>
                    <th>Consumer Confidence</th>
                    <script>
                        myFunction()
                        function myFunction() {
                            const foo = document.getElementsByClassName("bar")
                            foo[0].setAttribute("class", "table-info");
                            foo[1].setAttribute("class", "table-info");
                            foo[2].setAttribute("class", "table-info");
                        }
                    </script>
                </thead>
            </tbody>
        </table>
    </div>
</body>

I tried querySelectorAll() without success and also tried moving the script tag to other locations in without success.

My goal is to have the elements of the table receive their class before the page loads because Bootstrap will then color the fields of my table successfully.

CodePudding user response:

When you directly set the class attribute it overwrites any class (eg bar) that the element had. Since getElementsByClassName returns a live list, removing bar alters the content of your foo variable, removing the entry for the element that formerly had bar. If you just added the new class without removing bar this problem would stop. Try

foo[0].classList.add("table-info")

Also see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName

CodePudding user response:

I used queryselector. As the other answer says, this gets a live list and won't work. you should either cast the getelementbyclassname to an array or use queryselector.

Also here's an explanation on why that happens

Here's a working example with queryselector

<script>
      function myFunction() {
        var bars = document.querySelectorAll(".bar");
        for (var i = 0; i < bars.length; i  ) {
          bars[i].className = "table-info";
        }
      }
      myFunction()
    </script>

CodePudding user response:

Solution 1

myFunction()
function myFunction() {
  const foo = document.getElementsByClassName("bar")
  foo[0].setAttribute("class", "bar table-info");
  foo[1].setAttribute("class", "bar table-info");
  foo[2].setAttribute("class", "bar table-info");
}

Solution 2

myFunction()
function myFunction() {
  const foo = document.getElementsByClassName("bar")
  for(let f of foo) f.setAttribute("class", "bar table-info");
}

Solution 3

<thead>
  <th>Country</th>
  <th>Currency</th>
  <th>GDP</th>
  <th >Unenployment Rate</th>
  <th >Inflation Rate</th>
  <th >Interest Rate</th>
  <th>Balance of Trade</th>
  <th>Consumer Confidence</th>
</thead>
  • Related