Having trouble with a JavaScript problem when trying to add a new DIV class

I successfully implemented a random background script that assigns a unique bgimage to each page.

<script type="text/javascript"> 
function assignBackground() {
  let randomInt = Math.floor(Math.random() * 160);
    document.body.style.backgroundImage = "url('../../SITEWIDE/assets/bgimages/" + randomInt + ".jpg')";
    document.body.style.backgroundRepeat = "repeat";
    document.body.style.backgroundPosition = "absolute";
    document.body.style.backgroundSize = "cover";
}
</script>

<script type="text/javascript"> 
assignBackground();
</script> 

Now, I am facing an issue where I need to apply the background image to a DIV element with a specific class. The desired result is:

<div class="MySpecialDiv" style="background-image: url(../../main_img/slider/image1.jpg);"></div>  

I have tried using both document.getElementsByClassName and document.getElementById methods without success.

Any suggestions?

In response to this challenge, I attempted...

<script type="text/javascript"> 
function assignBackground() {
  let randomInt = Math.floor(Math.random() * 160);
    document.getElementById("heroBg").style.backgroundImage = "url('../../SITEWIDE/assets/bgimages/" + randomInt + ".jpg')";
    document.body.style.backgroundRepeat = "repeat";
    document.body.style.backgroundPosition = "absolute";
    document.body.style.backgroundSize = "cover";
}
</script>
<div class="MySpecialDiv"></div>

<body>
<script type="text/javascript"> 
assignBackground();
</script> 

as well as

<script type="text/javascript"> 
function assignBackground() {
  let randomInt = Math.floor(Math.random() * 160);
    document.getElementsByClassName("MySpecialDiv")[0].style.backgroundImage = "url('../../SITEWIDE/assets/bgimages/" + randomInt + ".jpg')";
    document.body.style.backgroundRepeat = "repeat";
    document.body.style.backgroundPosition = "absolute";
    document.body.style.backgroundSize = "cover";
}
</script>

<body>
<script type="text/javascript"> 
assignBackground();
</script> 

Unfortunately, the function does not execute when inspecting the HTML. It seems like the script is not running properly.

Answer №1

It appears that the changes you are trying to make in your code are affecting both the JavaScript and HTML, but they are not syncing up properly. The id you are attempting to target must correspond with an id specified in your HTML, and this HTML content should be within the <body> tags for it to display on the webpage.

Begin by focusing solely on your HTML structure:

<body>
    <div id="MySpecialDiv"></div>
    <script type="text/javascript"> 
        getImage();
    </script>
</body>

Once this is set up correctly, your script should successfully identify and modify the element with the designated id value of "MySpecialDiv":

let myDiv = document.getElementById("MySpecialDiv");
myDiv.style.backgroundImage = '...';
// additional modifications can follow

Answer №2

Appreciate the assistance! After some trial and error, I managed to get everything up and running. It might be a bit messy from a technical standpoint, but it's doing exactly what I need now. I accessed the DIV using both ID and CLASS. Here is the solution...

<section id="BUZZSAW" class="no-padding-top"> 
<div id="MySpecialDIV" class="MySpecialDIV"></div>
<script type="text/javascript"> 
function getImage() {
  let randomInt = Math.floor(Math.random() * 160);
    document.getElementById('herobg').style.backgroundImage = "url('../../SITEWIDE/assets/bgimages/" + randomInt + ".jpg')";
    document.body.style.backgroundRepeat = "repeat";// Background repeat
    document.body.style.backgroundPosition = "absolute";
    document.body.style.backgroundSize = "cover";
}
</script>
<body>
<script type="text/javascript"> 
getImage();
</script> 

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

Leveraging a specific section of an HTML5 CSS3 Bootstrap template in a separate template

As I create my website using a combination of free templates, I often find myself needing to merge elements from different designs. One specific example is wanting to incorporate the "Client Logo Slider" component from template 2 into my original template. ...

"Submit form data without reloading the page using the $_

I have an associative array that I am using to display images. I want to randomly select two or more pictures from these images with my code, but I have a couple of questions: How can I enhance the efficiency of my code? And is there a way to use JSON or ...

picture located in the top corner of the page within the diva triangle shape

Is there a way to position my photo on the same level as a div and have it overlap slightly? <div id='triangle-topleft'> <img id="photo" src="photo.png"> </div> #triangle-topleft { width: 0; heigh ...

The error message "Property 'push' of undefined in AngularJS" occurs when the push method is being called

I'm currently working on developing a basic phonebook web application to enhance my knowledge of Angular, but I've encountered an issue with this error message - "Cannot read property 'push' of undefined". Can anyone help me identify th ...

What is the best way to alter the color of the "checkmark" in an HTML checkbox using CSS?

Is it possible to change the color of the check mark in an HTML checkbox? Currently, on Windows XP using Firefox, Chrome, or IE, the check mark appears green. I am interested in changing the check mark within an INPUT type="checkbox" to be orange. ...

A guide on using Material UI - InputLabel in JavaScript

I'm currently integrating a form from this Codepen link into my project built with Codeigniter. However, I am encountering issues after incorporating material-ui into the CodeIgniter framework. The problems I am facing include an invalid token and an ...

Methods for comparing the current date and time to a specific time stored in a database

A database table contains the following values: "295fc51f6b02d01d54a808938df736ed" : { "author" : "James Iva", "authorID" : "JBvLC3tCYCgFeIpKjGtSwBJ2scu1", "geometry" : { "latitude" : 29.4241219, "longitude" : -98.49362819999999 ...

Retrieving solely the JSON data output from an AJAX request

I'm working with the following script: var test = $.ajax({ url : ("/areas/list"), type : 'GET', dataType : 'json', success : function(e) { // code here } }); The result stored in var text looks li ...

Semantic UI Footer allows you to easily create a stylish

Greetings! I'm new to the semantic-ui framework and I'm encountering an issue with the footer. My goal is to have the footer always stay at the bottom of the page without being fixed. Here's a snippet of my simple HTML code: <!DOCTYPE h ...

`CSS alignment issues`

Below is the HTML and CSS code that I am working with: .divOuter { width: 50%; margin: 0 auto; } .divInner1, .divInner2, .divInner3 { border: 1px solid; float: left; width: 150px; height: 150px; margin-left: 3px; margin-right: 3px; ...

Struggling to locate the Twitter direct message input box with Xpath in Selenium

I have been struggling to locate the textbox element using the find_element_by_xpath() method. Unfortunately, every time I try it, I receive an error stating that the element cannot be found. Here is the specific line of code in question: Despite attempti ...

What is the proper way to disable asynchronous behavior in JavaScript?

Can someone provide assistance on how to make the following jQuery ajax function asynchronous in this code? $.post(base_url+"search/questionBox/"+finalTopic+"/"+finalCountry+'/'+findSearchText+'/'+ID,function(data){ if (data != "") { ...

Caution: It is not possible to make updates on a component while inside the function body of another component, specifically in TouchableOpacity

I encountered this issue: Warning: Trying to update a component from within the function body of another component. Any suggestions on how to resolve this? Interestingly, the error disappears when I remove the touchable opacity element. ...

"Enable real-time editing with inline save/submit feature in

I'm struggling to figure out how to extract the modified content from a CKEditor instance and send it to a URL. I've been referencing something like this: but I can't seem to determine how to save the changes. Is there a way to post the up ...

When I try to refresh the page in the browser, the back button in Ionic is mysteriously missing

I am currently working on a project using Ionic. While testing the app in the browser, I encountered an issue where the back button disappears after navigating to the child state of one view and then refreshing the page. Upon inspecting the "$ionicHistory" ...

Utilizing Node, ObjectionJS, and Knex, we can establish a one-to-many relationship and retrieve the first associated row from the many

To simplify, I use two tables for a chatbox: Conversation and Message Conversations ID Status 1 open 2 open Messages Conversation ID Text Date 1 'ffff' (random date) 1 'asdf' (random date) 1 '3123123123&ap ...

PHP JSON array conversion

[ { "id":"26", "latitude":"10.308749502342007", "longitude":"123.88429984649656" }, { "id":"28", "latitude":"10.313816172726275", "longitude":"123.89030799468992" } ] I have retrieved this JS ...

Is it possible to conditionally redirect using Vue router?

I am in the process of creating a straightforward Vue application where the router links will be determined by the data retrieved from the server. The format of the data looks something like this: id: 1 path: "category_image/About.jpg" slug: &quo ...

Creating a layout design that adapts seamlessly to different screen

I am currently attempting to create the layout shown below for desktop using Bootstrap v4.3. https://i.sstatic.net/HCm7z.jpg This design should transition to the layout displayed below for mobile devices. https://i.sstatic.net/4Kzad.jpg However, upon r ...

The build for the React Native iOS app was successful, but unfortunately, it is not showing up as expected

I am currently working with react-native. My goal is to run my project on the iOS simulator. When I initially run the following code, everything functions correctly. sudo react-native run-ios --simulator "iPhone XR" However, after uninstalling my project ...