What causes divs and spans to be null values when attempting to adjust them using programming techniques?

Although I have experience styling logic with Ruby and Java, I am relatively new to front end development and JavaScript. I am encountering an issue where divs and spans are either undefined or null when I try to access them using methods like getElementById or getElementsByClassName. This has led me to create makeshift solutions just to make simple adjustments to backgrounds or add divs.

My most recent problem is outlined below:

var stars = document.getElementById("starContainer");

function starz() {
  for ( let i = 1; i <= 60; i++){
    var newDiv = document.createElement('div');
    newDiv.style.position = "absolute";
    newDiv.className = "star";
    newDiv.style.height = "15px";
    newDiv.style.width = "15px";
    newDiv.style.color = "white";
    newDiv.innerHTML = "star";
    newDiv.style.borderRadius = "15px";
    newDiv.style.backgroundColor = "white";
    newDiv.style.background = "radial-gradient(circle, rgba(255,255,255,1.0) 1%, rgba(255,255,255,0.0))";
    newDiv.style.left = setLeftPosition();
    newDiv.style.top = setTopPosition();
    
      stars.appendChild(newDiv);
  }
}

function setLeftPosition(){
  let min = Math.ceil(0);
  let max = Math.floor(1400);
  let rand = Math.floor(Math.random() * (max - min)) + min;
  
  return rand + "px";
}

function setTopPosition(){
  let min = Math.ceil(0);
  let max = Math.floor(490);
  let rand = Math.floor(Math.random() * (max - min)) + min;
  
  return rand + "px";
}
#scene {
position: relative;
  overflow: hidden;
  height: 1000px;
  width: 100%;
  background-color:rgb(0, 24, 63);
  background: linear-gradient(35deg,rgb(0, 24, 63) 10%, rgb(17, 0, 14));
}


#starContainer {
  color: white;
  z-index: -1;
  height: inherit;
  width: inherit;
}

  #ground { 
   position: absolute;
  height: 245px;
  width: 650px;
    border-left:20px solid transparent;
   margin-top: 800px;
 margin-left: 68%; 
  background-color: rgb(2, 2, 2);
  border-radius: 50px;
} 

#middle-ground {
  z-index: 2;
  position:absolute;
  border-bottom: 175px solid rgb(2, 2, 2);
  border-left: 150px solid transparent;
  border-top: 20px solid transparent;
  margin-top:792px;
  margin-left: 845px;
}


#slanted-border {
  position:absolute;
  width: 200px;
  border-bottom: 115px solid rgb(5, 5, 5);
  border-left: 150px solid transparent;
  border-top: 50px solid transparent;
  margin-top:845px;
  margin-left: 730px;
  
}
<!DOCTYPE html>
<html>
<head>


<!-- title & links to scripts & css---> 


<div id="scene" onload="starz()">
  <span id="starContainer">
    <!-- <p> I AM JESUS I AM JESUS</p> -->
  </span>
  <div id="slanted-border"></div>
  <div id="middle-ground"></div>
  <div id="lower-ground"></div>
  <div id="ground"></div>
</div>


</body>
</html>

Despite my efforts, this code does not seem to function as expected. When I log the "stars" variable (containing starContainer), it returns null, leaving me puzzled about what could be causing the issue. There have been other instances where fully styled divs were accessed one by one using class names and resulted in values returning as undefined for styled objects.

Interestingly, there are times when it does work! In a previous scenario, I resorted to manually grabbing each div by its ID, and the code worked fine. However, in this specific case, it works smoothly on CodePen (when set as an onclick event) and in the fiddle that I used to upload the code snippet, but fails when set as an onload, onfocus, or onclick event in an actual browser.

Any advice or guidance would be greatly appreciated.

Answer №1

Consider relocating the line

var stars = document.getElementById("starContainer");
inside the starz function to ensure it initializes on document load:
function starz() {
  var stars = document.getElementById("starContainer");
  for ( let i = 1; i <= 60; i++){
    var newDiv = document.createElement('div');
    newDiv.style.position = "absolute";
    newDiv.className = "star";
    newDiv.style.height = "15px";
    newDiv.style.width = "15px";
    newDiv.style.color = "white";
    newDiv.innerHTML = "star";
    newDiv.style.borderRadius = "15px";
    newDiv.style.backgroundColor = "white";
    newDiv.style.background = "radial-gradient(circle, rgba(255,255,255,1.0) 1%, rgba(255,255,255,0.0))";
    newDiv.style.left = setLeftPosition();
    newDiv.style.top = setTopPosition();
    
      stars.appendChild(newDiv);
  }
}

function setLeftPosition(){
  let min = Math.ceil(0);
  let max = Math.floor(1400);
  let rand = Math.floor(Math.random() * (max - min)) + min;
  
  return rand + "px";
}

function setTopPosition(){
  let min = Math.ceil(0);
  let max = Math.floor(490);
  let rand = Math.floor(Math.random() * (max - min)) + min;
  
  return rand + "px";
}

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

Error: Unable to locate module '@material/core/Grid'

After cloning a repository that is built with MUI, I noticed that certain components were already imported and working seamlessly. These components include: import Card from '@mui/material/Card' import CardActions from '@mui/material/CardAct ...

Struggling with integrating jQuery append into Backbone.js

Having trouble using jQuery.append() and backbonejs. Currently, when attempting to append, nothing happens (except the jQuery object is returned in the immediate window) and the count remains at 0. Manually adding the element has not been successful. I als ...

Incorporating a Bootstrap form within a form group

Can a select element be inserted inside a horizontal form in Bootstrap? I am trying to add a form with a select element inside a form group. Check out the code on Bootply. Note: Copy the code below as Bootply sometimes removes certain form tags. The is ...

The error "clearRect is not defined in javascript" occurs when the property is being called on an undefined object in the JavaScript

I've encountered a similar question before, but unfortunately, the solution provided didn't help me! I'm relatively new to JavaScript and have been struggling with this issue for nearly a day now without success. The structure of my class a ...

Similar to AngularJS, jQuery also provides a powerful tool for submitting forms

Recently, I've delved into the world of angularjs and have been truly amazed by its capabilities so far. One thing that took me by surprise was the lack of a simple solution for sending AJAX requests using the $http service. After hours of searching G ...

Requesting data with Ajax: utilizing parameters in the format of x-www-form-urlencoded

When adding parameters to a get/post request, it is important to encode them in application/x-www-form-urlencoded form. Is it necessary to encode values each time? Does JavaScript provide a method for encoding values? What options are available for caching ...

What could be the reason for the hover class not functioning properly in Tailwind?

Looking for some help with styling a button in Next.js using Tailwind. Specifically, I want the background color of the button to change when hovered over. I've been experimenting with code like this: <button className="rounded-full bg-gradie ...

What does the error message "TypeError: Bad argument TypeError" in Node's Child Process Spawn mean?

Every time I execute the code below using node: var command = "/home/myScript.sh"; fs.exists(command, function(exists){ if(exists) { var childProcess = spawn(command, []); //this is line 602 } }); I encounter this error: [critical e ...

"When attempting to output HTML using PHP, be sure to include a backslash () before special characters like

One issue I am facing is with a PHP code that retrieves HTML content from the database and uses echo to display it on my page. The problem arises when I use echo, as the HTML output ends up looking like this: <div class="\&quot;schema-faq- ...

Tips for guaranteeing blocking within a loop in Node.JS

While I usually enjoy the asynchronous nature of Node.JS and its callback-soup, I recently encountered an issue with SQLite that required a certain part of my code to be run in a blocking manner. Despite knowing that addressing the SQLite problem would mak ...

There seems to be a lack of information appearing on the table

I decided to challenge myself by creating a simple test project to dive into Angular concepts such as CRUD functions, utilizing ngFor, and understanding HttpClient methods (specifically get and post). After creating a Firebase database with an API key and ...

The absence of FontAwesome Icons is apparent

In the <head> section of my code, I include the following: <script href="https://kit.fontawesome.com/a076d05399.js"></script> Within some of my buttons, I have the following code: <div class="scroll-up-btn"> ...

Passing a JSON file name as an argument to a command line in Node.js

When I run app.js using the command node app.js, it will execute const inputData = require('./input.json'); Now, my question is - can I pass the file name as an argument to const inputData = require('./file.json'); directly from the co ...

Wrapper Div at the Center

I'm currently working on aligning my webpage in the center using the following CSS: .wrapper { display: flex; align-items: stretch; background: #fafafa; /*max-width: 1520px; */ box-shadow: 1px 1px 12px rgba(0, 0, 0, 0.1); text ...

Eliminate the jQuery AJAX timestamp from the URL parameters

Is there a way to eliminate the jQuery AJAX cache buster code (_=3452345235) from string URLs? While working on a global AJAX fail handler, I need to identify which URL failed. However, every time I locate the failed request's URL, the jQuery cache q ...

How to Route in Angular 5 and Pass a String as a Parameter in the URL

I am currently working on an Angular project that focuses on geographic system data. The concept is as follows: I have a component with the route: {path: 'home'}. I aim to pass a geojson URL along with this route, making it look like this: {pat ...

Setting a background image in vanilla-extract/css is a straightforward process that can instantly enhance

I am brand new to using vanilla-extract/CSS and I have a rather straightforward question. I am attempting to apply a background image to the body of my HTML using vanilla-extract, but I am encountering issues as I keep getting a "failed to compile" error. ...

Having trouble getting padding to work inside a pre block, even when using a wrapper div?

Snippet of HTML Code: <div class="prewrap"> <pre> stepsize = .01 samplestimes = 30 universex = seq(-1, 1, stepsize) universey = sin(pi * universex) </pre> </div> Sample CSS Styles: #prewrap { background-color: #e3e3e3; pa ...

What is the best method to retrieve a specific data field from a JavaScript object using jQuery?

I am new to the world of jQuery and JavaScript and I am unsure if this question has been asked before. Despite searching extensively, I have not found a relevant answer to my specific query. My goal is to create a web crawler using Apify. I am looking to e ...

What is the best method for swapping out an iframe with a div using Javascript?

Having an issue with loading an external HTML page into an iFrame on my website. Currently facing two main problems: The height of the iFrame is fixed, but I need it to adjust based on the content's height. The content inside the iFrame does not inh ...