Clicking on the background does not alter the onclick function

Can anyone help me troubleshoot my code? My function load() isn't changing the background of .firstDiv for some reason.

I've checked multiple times but I can't seem to spot any errors.

function load() {
document.getElementsByClassName("firstDiv").style.backgroundImage = "url('https://static.pexels.com/photos/140945/pexels-photo-140945.jpeg')";
}
.firstDiv, .secondDiv {
  width: 50%;
  height:100vh;
  float: left;
}

.firstDiv {
  background-image: url("https://static.pexels.com/photos/200303/pexels-photo-200303.jpeg");
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  box-shadow: inset 0 0 0 1000px rgba(0,0,0,.2);
  }
<div class="firstDiv"></div>

<div class="secondDiv">
  <button onclick="load()">Change background</button>
</div>

Answer №1

The issue can be found in the following line of code:

document.getElementsByClassName("firstDiv")...

To resolve this, you should update the line to:

document.getElementsByClassName("firstDiv")[0]

Here is the corrected snippet:

function load() {
  document.getElementsByClassName('firstDiv')[0].style.backgroundImage = "url('https://static.pexels.com/photos/140945/pexels-photo-140945.jpeg')";
}
.firstDiv, .secondDiv {
    width: 50%;
    height:100vh;
    float: left;
}

.firstDiv {
    background-image: url("https://static.pexels.com/photos/200303/pexels-photo-200303.jpeg");
    background-position: center;
    background-size: cover;
    background-repeat: no-repeat;
    box-shadow: inset 0 0 0 1000px rgba(0,0,0,.2);
}
<div class="firstDiv"></div>
<div class="firstDiv"></div>

<div class="secondDiv">
    <button onclick="load()">Change background</button>
</div>

Answer №2

When updating the load() function, ensure to modify it in a way that it utilizes the initial element retrieved by getElementsByClassName, considering that it can return various elements.

document.getElementsByClassName("firstDiv")[0]...

Answer №3

If you're utilizing the getElementByClassName method, it's important to specify the item number using an index like [0], or alternatively you can use the id attribute.

Example with Class Name:

function changeBackground() {
document.getElementsByClassName("firstDiv")[0].style.backgroundImage = "url('https://static.pexels.com/photos/140945/pexels-photo-140945.jpeg')";
}
.firstDiv, .secondDiv {
  width: 50%;
  height:100vh;
  float: left;
}

.firstDiv {
  background-image: url("https://static.pexels.com/photos/200303/pexels-photo-200303.jpeg");
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  box-shadow: inset 0 0 0 1000px rgba(0,0,0,.2);
  }
<div class="firstDiv"></div>

<div class="secondDiv">
  <button onclick="changeBackground()">Change background</button>
</div>

Using ID

  1. Assign ID e.g
    <div id="firstDiv"></div>
  2. Javascript Code:

    document.getElementById("firstDiv").style.backgroundImage = "url('https://static.pexels.com/photos/140945/pexels-photo-140945.jpeg')";
    

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to verify the file extension in a multi-input form during an upload process?

I am looking for a solution that requests users to upload 4 different files when filling out the form. Check out this example of one of the inputs: <div class="custom-file"> <input type="file" class="custom-file-input" accept="video/*" id="v ...

Utilizing global variables in Vue.js while working with the CLI template

How can I create a global variable in my Vue.js app that is accessible by all components and modifiable by any of them? I am currently utilizing the CLI template. Any recommendations on how to achieve this? Appreciate your assistance. Dhiaa Eddin Anabtaw ...

What causes jquery height and javascript height to both be returned as 0?

I'm facing an issue with a visible div on my screen - despite being visible, its height always returns as 0. I've attempted various jQuery and JavaScript methods to retrieve the height, but it consistently shows as 0. Here's the structure of ...

The presentation of an HTML table varies between Gmail and web browsers

<table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td> <table width="100%" height="131" border="0" cellspacing="0" cellpadding="0"> <tr> <td wid ...

Leveraging HTML5 file uploads alongside AJAX and jQuery

While there are questions with similar themes on Stack Overflow, none seem to quite fit the bill for what I am looking for. Here's my goal: Upload an entire form of data, including a single file Utilize Codeigniter's file upload library So fa ...

`<div>` element with a class of "button" that listens for

I've been attempting to use a userscript to automate a button click. Inspecting the element reveals the button code as: <div class="q-w-btn cl"></div> Unfortunately, the button lacks an id attribute, making it difficult for me to select ...

Maintaining the image's aspect ratio while cropping it to fit within the maximum or minimum height

Is there a way to make an image responsive by resizing it while keeping its aspect ratio intact at all sizes? I want the height of the image to stay fixed above 650px, cropping the top and bottom to maintain the ratio without stretching. Additionally, I do ...

Unlocking the potential of Vue within shadow dom environments

I am facing an issue with a shadow DOM that includes the root element and a Vue component. <template> <div class="container"> <div id="app"></div> </div> <script src="http://my-site.com/app/js/vue-compo ...

Turn off jQuery on certain pages while keeping the styling intact?

Hey there, I'm currently in the process of developing a mobile website using jquery. I was wondering if it's possible to disable jQuery on certain pages while still retaining the styles, such as the navigation bar. The reason for wanting to disab ...

Is there a way for me to enable the user to easily download the HTML file?

Is there a way to create an Invoice in HTML rather than a PDF-file and provide the user with an easy download link for the HTML-file? When I simply link to the HTML file, it only seems to be "temporarily downloaded" and viewed in the user's web brows ...

Leveraging PHP to dynamically insert image file names into a directory for populating the HTML img src attribute in a Bootstrap

I am trying to dynamically populate a Bootstrap carousel with images from a folder by using PHP to scan the image files. However, instead of displaying the images in the carousel, only the names of the images are being listed. Below is my code, and I have ...

Is there a child missing? If so, add a class

I need to add the class span.toggle if the parent element of li does not have a child ul element. click here to view on codepen Snippet of HTML: <html lang="en"> <head> <meta charset="UTF-8> <title>No Title</title>& ...

Creating distinct web addresses for various sections of vue.js pagination

I've implemented pagination using vue.js for my website's gallery. However, I'm facing an issue where the URL doesn't change when navigating through pages and upon page refresh, it always resets to page 1. My goal is to have the URL ref ...

Where do JQuery and framesets vanish to?

Whenever I attempt to use the console to create an element with the tag frameset, it returns no result: $('<div id="content" data-something="hello" />') => [<div id=​"content" data-something=​"hello">​</div>​] $(&apo ...

Challenger arises in the realm of Chakra UI styling

Recently, I've encountered an issue with displaying a card using chakra UI and next js. The CSS of chakra UI seems to be messed up, causing all my components to display incorrectly. It was working perfectly fine until yesterday. I tried deleting the . ...

Issue with Angular custom tag displaying and running a function

I have created a custom HTML tag. In my next.component.ts file, I defined the following: @Component({ selector: 'nextbutton', template: ` <button (click) = "nextfunc()">Next</button> ` }) export class NextComponent{ nextfunc( ...

Javascript dynamically generates CSS animations

I need assistance creating a div with a CSS3 animated timer inside it when a button is clicked. Here is the code I have been working on: http://jsfiddle.net/arcco96/y5nov6rz/1/. Unfortunately, the div is not being created as expected. I believe the code sh ...

What's the issue with the addClass function not working as expected?

I am currently integrating the website's navbar using PHP, which is why I am unable to use class="active" to highlight the active tab on my navigation bar individually. To solve this issue, I attempted to add the active class to the corresponding tab ...

Tips for integrating CSS with Material UI TableContainer

I have utilized Material UI Grid to display data in a chart. However, the appearance of the chart does not match my expectations. Instead of resembling the desired "dense table," it looks different: Actual Look of the Chart Below is the code snippet I ha ...

Transfer the data from a post request through routes following the MVC pattern

Encountering an issue when attempting to submit a post form with username and password, as an error stating Cannot POST /validateUser is displayed. The structure of my form is as follows: <!DOCTYPE html> <html> <head> <title> ...