2

I want to change the background of a div that has an "input-group-addon" class, when I click in the input element:

<div class="form-group col-sm-12 col-md-5">
    <label class="sr-only" for="exampleInputEmail">Email address</label>
    <div class="input-group" >
        <div class="input-group-addon">
            <img src="pictures/email.png" alt="Email" />
        </div>
        <input type="email" class="form-control" id="exampleInputEmail" placeholder="Email Adress" onclick="changeBackground()">
    </div>
</div>

I create javascript file background.js:

function changeBackground() {
    var el = document.getElementsByClassName('input-group-addon');
    el.style.backgroundColor = "#cc0c8e";
}

and I inserted it at the end of the html file:

<script src="js/background.js"></script>

But it doesn't work. I had to make a mistake, but I did not see it... Thank you in advance.

  • `el[0].style.backgroundColor` do this, because `getElementsByClassName` returns array of element with given class name – Durga Aug 04 '17 at 09:50
  • I think you have to add [0] to el in line el.style. – dec Aug 04 '17 at 09:50

2 Answers2

1

document.getElementsByClassName() returns an array-like object. To update an element you've to specify an index.

var el = document.getElementsByClassName('input-group-addon')[0];
Aer0
  • 3,792
  • 17
  • 33
0

Your problem - getElementsByClassName returns array of elements

Just do it with: el[0].style.backgroundColor = '#cc0c8e';

And you also can use document.querySelector('.input-addon-group') instead getElementsByClassName

fabledva
  • 1
  • 1