Error when calling a function, Cannot set Property 'src' of null

Asked

Viewed 86 times

-4

Hello, I’m doing a project for study. When I call the function, the code presents an error. The only thing I want to do in this function is just swap one image for the other when clicking and so also change the background color.

    <div class="content">
        <div class="textBox">
            <h2>That's What<br><span>I like</span></h2>
            <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
                Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, 
                when an unknown printer took a galley of type and scrambled it to make a type specimen book. 
            </p>
            <a href="#">View All Products</a>
        </div>        
            <div class="imgBox">
                <img src="./images/pepsi001.png" alt="pepsi">    
        </div>

    </div>

    <ul class="thumb">
        <li><img src="./images/pepsi001.png" onclick="imgSlider('pepsi001.png');changerBgColor('#0062be')"></li>
        <li><img src="./images/pepsi002.png" onclick="imgSlider('pepsi002.png');changerBgColor('#360c2c')"></li>
        <li><img src="./images/pepsi003.png" onclick="imgSlider('pepsi003.png');changerBgColor('#1e1e1e')"></li>
    </ul>

    <ul class="sci">
        <li><a href="#"><img src="./images/facebook.png" alt=""></a></li>
        <li><a href="#"><img src="./images/instagram.png" alt=""></a></li>
        <li><a href="#"><img src="./images/twitter.png" alt=""></a></li>
    </ul>

</section>

<script>
    function imgSlider(anything) {
        document.querySelector('.pepsi').src = anything;
    }

    function changerBgColor(color) {
        const sec = document.querySelector('.sec');
        sec.style.background = color;

    }
</script>
  • The HTML list of products ended up being interpreted as a list of the question itself. Try to fix the post for the HTML code to appear.

  • Change made.

1 answer

1

In function imgSlider, you used the class Pepsi to select the images that must be exchanged. However, there is no item in HTML that has this class, and this makes it impossible to find the elements, causing the browser find only null. For the code to work, add the attribute class="Pepsi" on all the HTML items you want to undergo transformation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.