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

Converting a key-value pair string into an array in PHP: A comprehensive guide

When the checkbox is selected, I will extract the values listed below: attribute_value:samsung, attribute_id:1, spec_group_id:2, prod_id:1 To convert the above string into an array format and obtain a single array outside of the loop. Therefore, if I wa ...

Challenges with moving images in Unslider

There seems to be an issue with the unslider-arrows on the unslider banner. The images are not sliding properly when transitioning to the next image without user input. Instead, they resize from small to full size starting at the top of the .banner div. ...

Tips for troubleshooting ImageArray loading issues in AngularJS

Having some trouble learning Angular and getting stuck with this Image array. Can someone please help me understand what's wrong with my code and how to fix it? FilterAndImages.html <!DOCTYPE html> <html ng-app="store"> <head> < ...

Drop Down Automation with Selenium IDE

Currently in the process of automating a User Acceptance Testing (UAT) for a software project at my company. I've completed all the typical tasks like recording actions and clicking on buttons, but ran into an issue with a drop-down menu. The problem ...

Is there a way to include a button at the top of the Notiflix.Loading() overlay for closing or stopping it?

I've integrated the "notiflix" library into my project, and I'm currently using notiflix.loading.pulse() for a lengthy process. While this works perfectly fine, I would like to add a button (for closing/stopping the process) on top of the loading ...

When I click on a link to redirect it, I am confronted with a bizarre rectangle that

When attempting to create redirects using images, I encountered a small issue. Take a look at this screenshot: This is the item in question: <p><div><a title="Home" href="/home"><img src="/icons/home.svg" ...

What is the best way to ensure that the content on my webpage stays below the navbar, no matter the height of the

I've been working on my homepage layout and encountered an issue with positioning the content below the navbar, which is centered on the page. Every time I adjust the window height, the content shifts. How can I ensure that it stays fixed below the na ...

Reposition text below images in Meta Slider

I have a website where I am utilizing Meta Slider within Wordpress. I would like to position the captions below the images instead of on top of them. Meta Slider claims this feature is only available in the Pro version, but could it be achieved by adjustin ...

AngularJS routing to a specific view

Here is some code snippet you may find helpful: This code will render the /result content every time the defaultview function is called using the $route service: angular.module('myapp').controller ('ResultController',['$route ...

Uniform Fixed Width for Material UI Table Cells

Below is a Material UI Table with columns set to a fixed size of 205px each, and the table itself set to 100% width. However, when there isn't enough space available, the columns do not shrink according to the text inside them, remaining stuck at 205p ...

Is it feasible to organize checkboxes into columns using CSS?

Can checkboxes be reflowed into columns horizontally as the container's height changes dynamically with an unknown number of checkboxes? Here is a visual representation to illustrate the concept: Height = 180px (20px * 9 checkboxes): [ ] Checkbox 1 ...

Color Swap Hover Animation

I need help implementing a color switch on hover, but I'm facing an issue where the text (within a span) is within a list item. Currently, the color changes only when hovering over the text itself, but I want it to change when hovering over the entire ...

Vanishing essence

http://jsfiddle.net/ddGHz/1004/ //html <div id = "anglereturn"/> <div class="box"></div> //js, jquery var box=$(".box"); var boxCenter=[box.offset().left+box.width()/2, box.offset().top+box.height()/2]; $(document).mousemove(function ...

String iteration with Stylus

Is there a way to remove the brackets and the quotation marks when putting media queries into an object and looping over them? The code works well, but the stylus is causing the output to have unwanted characters. Here's my code: $maxBreakpoints = { ...

Using JavaScript to toggle the iron-collapse property

I've implemented multiple <iron-collapse> elements with unique IDs, each one corresponding to a <paper-icon-button>. On screens wider than 650px, I can interact with the <iron-collapse>s using their respective buttons. But on narrow ...

Tips on transferring information from AngularJS to a remote server using ngResource

Looking for guidance on utilizing the ngResource module? To send data to a server. To retrieve data from a server. I am attempting to send data to a Solr server. Utilizing AngularJS API. Using npm package manager to install packages to my application. Th ...

Why do my paths encounter issues when I alter the manner in which I deliver my index.html file?

I recently made a decision to change the method of serving my index.html file from app.use('/', express.static(__dirname + '/..')); to app.get('/', function(req, res) { res.sendFile(path.join(__dirname + '/../index.htm ...

The button's onclick function is not triggering with just one click

I am having trouble with a JavaScript function not being called on the first click. I have to click the button multiple times for it to execute. Here are the methods I have attempted so far: <a href="javascript:delete_todo(4);void(0)"><img border ...

"Troubleshooting the Issue of Unsuccessful Retrieval of Added Row Text Value

Struggling with retrieving text values from dynamically added rows? The first row data converts fine to PDF, but how do you push data through AngularJS from dynamic rows? Appreciate any help. See my code snippet below: <table id='myTable&a ...

What is the reason for the malfunction of this JavaScript code designed for a simple canvas operation?

I'm having trouble with the code below. It's supposed to display a black box on the screen, but for some reason it's not working properly. The page is titled Chatroom so at least that part seems to be correct... <html> <head> &l ...