Creating and adding nested div elements with the power of JavaScript

My goal is to utilize JavaScript for updating the CSS layout as the webpage loads. Below is the code I have been working on:

var container = 0; // Total UI Container
var containerTitle = 0; // Title Container

var article = 0; 
var articleTitle = 0;

var divName = 0; // Temporary variable for article id names
var divNameT = 0; // Temporary variable for title id names

function setLayout(id) {
    container = document.getElementById(id);

    for(var x = 0; x < 18; ++x) {
        // CREATE CONTAINER FOR ALL PANELS
        divName = "articleCon"+ x;
        article = document.createElement('div');
        article.id = divName;
        // SET UP CSS STYLE
        article.style.cssText = 'height: 205px; width: 300px; background: red; margin-right: 20px; margin-bottom: 20px; display: block; float: left;';

        setNewsTitle(count,divName); // Call function to set Title Panel

        container.appendChild(article);
    }
}

function setNewsTitle(count,id) {
    containerTitle = document.getElementById(id);
    // CREATE CONTAINER FOR TITLE
    divNameT = "articleTitle"+ count;
    articleTitle = document.createElement('div');
    articleTitle.id = divNameT;
    // SET UP CSS STYLE
    articleTitle.style.cssText = 'position: absolute; height: 45px; width: 100px; background: yellow; display: inline;';

    containerTitle.appendChild(articleTitle);
}

Everything works fine when I compile my code without including the call to function setNewsTitle(count,id). However, the problem arises when this function call is included - the page shows up blank with no content displayed.

I attempted to attach screenshots for better clarity, but unfortunately, I do not yet have sufficient reputation to do so.

Answer №1

Give it a shot...

    Add the article to the container.
    Call the function setNewsTitle with parameters x and divName to set the title panel.

Make sure the article is added before running the setNewsTitle function, as it looks for the element by id. Also, remember that you should use x instead of count...

Check out this example on jsFiddle: http://jsfiddle.net/examplelink123/

Answer №2

For a different approach, consider using the appendChild method in the DOM structure before calling the setNewsTitle function. Additionally, replace the count variable with x :

var container = 0; // Total UI Elements
var containerTitle = 0; // Title Container

var article = 0; 
var articleTitle = 0;

var divName = 0; // Temporary variable for article IDs
var divNameT = 0; // Temporary variable for title IDs

function setLayout(id) {
    container = document.getElementById(id);

    for(var x = 0; x < 18; ++x) {
        // CREATE CONTAINER FOR ALL PANELS
        divName = "articleCon"+ x;
        article = document.createElement('div');
        article.id = divName;
        // SETUP CSS STYLE
        article.style.cssText = 'height: 205px; width: 300px; background: red; margin-right: 20px; margin-bottom: 20px; display: block; float: left;';

        container.appendChild(article);

        setNewsTitle(x,divName); // Call function to set Title Panel

    }
}

function setNewsTitle(count,id) {
    containerTitle = document.getElementById(id);
    // CREATE CONTAINER FOR TITLE
    divNameT = "articleTitle"+ count;
    articleTitle = document.createElement('div');
    articleTitle.id = divNameT;
    // SETUP CSS STYLE
    articleTitle.style.cssText = 'position: absolute; height: 45px; width: 100px; background: yellow; display: inline;';

    containerTitle.appendChild(articleTitle);
}

Answer №3

Your code has a couple of issues that need addressing:

  1. One problem is that you haven't added the element to the DOM yet, causing document.getElementById in your setNewsTitle() function to not find anything.

  2. Another issue lies in the method call to setNewsTitle(count,id). You are passing "count", which does not exist. Instead, you should be calling it as setNewsTitle(x, divName), but only after the call to container.appendChild(article).

The revised setLayout function would look like this:

function setLayout(id) {
    container = document.getElementById(id);

    for(var x = 0; x < 18; ++x) {
        // CREATE CONTAINER FOR ALL PANELS
        divName = "articleCon"+ x;
        article = document.createElement('div');
        article.id = divName;
        // SETUP CSS STYLE
        article.style.cssText = 'height: 205px; width: 300px; background: red; margin-right: 20px; margin-bottom: 20px; display: block; float: left;';

        // Add it to the DOM first
        container.appendChild(article);
        // Pass "X" instead of count
        setNewsTitle(x,divName); // Call function to set Title Panel
    }
}

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

Changing the color of a pressed Bootstrap 4 button

After making changes to the bootstrap css class of the button such as the color, font size, and font color, I noticed that when I click and hold the mouse on the button, the color changes. Even though I set the color to green, when I click and hold the mo ...

Implementing the adding functionality within an ejs file

I'm currently working on a project that involves fetching data from an API using a simple JavaScript file upon clicking a button. Initially, everything was functioning properly when both the HTML file and JS file were in the same folder, and I could a ...

Unfortunate Outcome: CSS Request Results in 404 Error

Recently, I made a transition from having a single-page website to using an express server for my website. During this process, I had to modify the file paths. However, I am encountering difficulties in loading my css and js files. Upon inspecting the dev ...

jQuery draggable elements can be easily dropped onto droppable areas and sorted

I need help with arranging the words in the bottom tiles by sorting them from "Most Like Me" to "Least Like Me" droppable areas. Currently, I am able to drag and drop the words into different boxes, but it ends up stacking two draggable items on top of eac ...

mobile screens causing bootstrap columns to overlap

The code I am working with is shown below: <div class="container"> <div class="col-md-3 calendar"> </div> <div class="col-md-9"> <button></button> (more buttons...) </div> < ...

The results returned by the jQuery find() function vary across various pages

One interesting feature on my website is the header bar with a search function. I have implemented a function that involves resizing boxes to contain search results. On one specific page, this function works like a charm: $(".suggestionCategory").each(fu ...

React Select only enabling single selection at a time

Currently, I am in the process of updating my react app to version 16.8 and also updating all associated libraries. One issue that has come up is with two drop-down selects from Material UI. Since the update, the multi-select option no longer allows multip ...

Utilize Angular's $location to add or update the current URL parameter

I'm working on a function for handling multiple parameters in the URL when clicking an element. Specifically, I need to check if parameter pthree exists, update it to a new value without duplicating, and if it doesn't exist, append it to the curr ...

Issue with margin-top in combination with clear:both does not function as expected

<div style="float: left;">Left</div> <div style="float: right;">Right</div> <div style="clear: both; margin-top: 200px;">Main Data</div> What is causing the margin-top property to not work as expected for 'Main Dat ...

AngularJS ng-repeat - cascading dropdown not refreshing

I'm dealing with an AngularJS issue where I'm trying to create a cascade dropdown like the one below: <div class="col-sm-2 pr10"> <select class="PropertyType" ng-controller="LOV" ng-init="InitLov(140)" ng-model=" ...

Ways to unlock all the information windows in Google Maps

Is it possible to automatically display all info windows on the map when it is first opened, eliminating the need for users to click on markers? In other words, I would like all info windows for all markers to be shown by default when the map is opened. ...

Guidance on incorporating static files with Spring MVC and Thymeleaf

I'm seeking guidance on how to properly incorporate static files such as CSS and images in my Spring MVC application using Thymeleaf. Despite researching extensively on this topic, I have not found a solution that works for me. Based on the recommenda ...

Leverage the Express JS .all() function to identify the specific HTTP method that was utilized

My next task involves creating an endpoint at /api that will blindly proxy requests and responses to a legacy RESTful API system built in Ruby and hosted on a different domain. This is just a temporary step to transition smoothly, so it needs to work seam ...

Having trouble uploading the file to Firebase storage

While attempting to upload files to Firebase using React, I encounter a perplexing issue. The file upload progress bar hits 100%, only to present me with an unfamiliar error message: { "error": { "code": 400, "message": "Bad Request. Could not c ...

Alert: The lack of boundary in the multipart/form-data POST data has been detected in an unknown source on line

I am currently developing a file uploader that uploads an image when the input changes. Here is the code for my HTML form: <form method="post" enctype="multipart/form-data"> <input name="uploaded[]" type="file" id="file_upload"/> </for ...

Arranging HTML Lists in Perfect Order

I am working with an HTML list that contains links styled as background images rather than text. The container is 200px tall and I would like the links to be centered inline within the container. Usually, I would use line-height:200px; for text to achieve ...

"Implementing a dynamic search for IMG SRC using ng-src in AngularJS: a step-by-step

I am encountering an issue with setting the source of an image based on a variable that may initially be null. When I set the source to include the path and the variable followed by PNG, I get an error because the variable is null at the beginning. How can ...

I'm having trouble making a Javascript ajax request to my Web API controller page. It seems like I just can't figure out the correct URL

Currently, I am facing an issue with my registration page where I am attempting to save input fields into a new record in the Users table. <button class="btn-u" type="submit" onclick="submitclicked()">Register</button> The click event trigger ...

Python and website submission button without an action attribute

I'm currently working on a Python program that interacts with an online store. So far, I've successfully located the desired item and accessed its page using BeautifulSoup. However, I'm struggling with clicking the "Add to cart" button. Most ...

What category does React.js fall under - library or framework?

Hey there! I've noticed that sometimes people refer to React JS as a library, while others call it a framework. Can you shed some light on which term is more accurate? ...