I am trying to access the background property of a specific section. In this case, I want to access the background property on the left section of my page. There is currently a placeholder image that I have set up, but I want that image to change if the user presses on a button on the right side.
This is the current code I have on the button titled "Model 2" . When I click on the Model 2 button, I get no error in the browser console, and it seems to be that the background image only turns a bit dark.
I am not sure if im just not accessing the right ID for the section, or if im doing something wrong. Using ID finder, the ID for the left section is: section[data-section-id="6642cac4e9abab7cc0dd30e9"]. I have also querySelecting this into the mainSection but the console would output that the id couldnt be found.
I simply just need to be able to access the DOM element that will allow me to change the background image of that section.
<button id='model-2-button'>Model 2</button>
<script>
document.addEventListener('DOMContentLoaded', function() {
const buttonTwo = document.querySelector('#model-2-button');
const mainSection = document.querySelector('.section-border');
buttonTwo.addEventListener('click', function(event){
event.preventDefault();
buttonTwo.textContent = "Button clicked";
if (mainSection) {
const mainSectionImg = mainSection.querySelector('.section-background img');
if (mainSectionImg) {
// Adding a cache-busting query parameter to force image reload
const newSrc = 'https://images.squarespace-cdn.com/content/v1/5e4b3cfd445a6a5feb18f718/88a13f9c-57b4-4ffa-98e6-712593ba556d/test1.jpg?timestamp=' + new Date().getTime();
mainSectionImg.src = newSrc;
// Force reload by removing and re-adding the image
const parent = mainSectionImg.parentNode;
parent.removeChild(mainSectionImg);
parent.appendChild(mainSectionImg);
} else {
console.error('Image element not found in the targeted section');
}
} else {
console.error('Section with class "section-border" not found');
}
});
});
</script>
<style>
#model-2-button {
color: black;
background: white;
border: 1px solid rgb(225, 222, 218);
cursor: pointer;
border-radius: 15px;
transition: border 0.5s ease 0s;
padding: 12px 40px;
width: 327px;
}
#model-2-button:hover {
border-color: black;
}
</style>