1

I have three divs with the same class name that I want to alter the height and color of using JavaScript. My code is breaking, not sure why. I've looked at answers to similar problems on here and my code seems to be the same as the solutions.

Any idea on where my code is breaking and how to fix it ?

<HTML>
<head></head>
<body>
    <div class="bar"></div>
    <div class="bar"></div>
    <div class="bar"></div>
    <script>
        function altSize() {
            var bar = document.getElementsByClassName("bar");
            bar.style.height = 200px;
            bar.style.background = 'red';
        }
        altSize();
    </script>
</body>
</HTML>
1
  • 1
    .bar{height: 200px;} why not this? Commented Dec 5, 2013 at 16:47

1 Answer 1

5

It's breaking here:

      bar.style.height=200px;

The reason is that 200px is not something you can assign in JS, it reads the 200 and doesn't know what to do with the px, it's not a valid number.

Moreover, getElementsByClassName returns a NodeList and not a single element.

Fix it with

      for(var i=0;i<bar.length;i++){
           bar[i].style.height="200px";
      }

fiddle

Sign up to request clarification or add additional context in comments.

3 Comments

I think you mean getElementsByClassName :)
Do I need to create an array to put the div element classes in?
@moonshineOutlaw no, you don't. When you perform a getElementsByClassName query it returns a NodeList (Not exactly an array but can be iterated just the same). Below the last code sample in my answer I have a fiddle - you might want to check that out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.