0

Currently I am trying change the background image of a div container using its class name on button click event, and I get this error on the console "Cannot set property backgroundImage of undefined". Unable to understand what is wrong in the code.

<!DOCTYPE html>
<html>
    <head>
        <script>
            function slide()
            {
                var ele = document.getElementsByClassName("banner-section");
                ele.style.backgroundImage = "url(image-2.png)";
            }
        </script>
    <head>
    <body>
        <!--Main Container Start-->
        <div class="main-container">

            <!--Header Section Starts-->
            <div class="header-section">
                <!--<img id="logo" src="images/logo/logo-2.png">-->

                <!--Navigation Section Starts-->
                <div class="navigation-section">
                    <ul>
                        <li><a href="#">Home</a></li>
                        <li><a href="#">About Us</a></li>
                        <li><a href="#">Our Services</a></li>
                        <li><a href="#">Portfolio</a></li>
                        <li><a href="#">Contact Us</a></li>
                    </ul>
                </div>
                <!--Navigation Section Ends-->

            </div>
            <!--Header Section Ends-->

            <!--Banner Section Starts-->
            <div class="banner-section" id="x">
                <button onclick="slide2()">Previous</button>
                <button onclick="slide()">Next</button>

            </div>
            <!--Banner Section Ends-->
        </div>
        <!--Main Container Ends-->

    </body>
</html>
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Lalit Pal
  • 310
  • 1
  • 5
  • 14

1 Answers1

4

Try

var ele = document.getElementsByClassName("banner-section")[0]

because getElementsByClassName returns an array of elements.

Andrea
  • 6,032
  • 2
  • 28
  • 55
  • "Also, move your JS code to the end, it could not have the DOM's visibility, there." — DOM visibility depends on when a function is *called* not when it is defined. – Quentin Oct 07 '16 at 10:42
  • "because getElementsByClassName returns an array of elements." — It is a live HTMLCollection, not an array. – Quentin Oct 07 '16 at 10:42