What is the best way to customize the color and width of div elements on a webpage?

I am trying to customize the colors and widths of multiple div elements using arrays and a for loop in my HTML code. However, I am having trouble figuring out how to properly implement this. Specifically, I want 5 divs on the page with different background colors and widths.

If anyone has experience with this type of task and can offer some guidance, I would greatly appreciate it. Thank you!

    <html>
    <head>
        <title>Customizing Div Elements</title>
    <script type="text/javascript">

        var colorArray = Array("#F00","#FF0","#0F0","#0FF","#00F");
        var widthArray = Array("20", "40", "60", "80", "100");

        {
            for (i=0; i<5; i++)
            {
                document.getElementById('div'+i).style.backgroundColor = colorArray[i];
                document.getElementById('div'+i).style.width = widthArray[i];
            }
        }

        </script>
    </head>
    <body>
        <div id="div1">div1</div>
        <div id="div2">div2</div>
        <div id="div3">div3</div>
        <div id="div4">div4</div>
        <div id="div5">div5</div>
    </body>
</html>

Answer №1

Revise your for loop to:

for (i=1; i <= 5; i++) {
    document.getElementById('div'+i).style.backgroundColor = color[i-1];
    document.getElementById('div'+i).style.width = width[i-1] + "px";

Replace the code:

document.getElementById('div'+i).style.width = width[i];

with:

document.getElementById('div'+i).style.width = width[i-1] + "px";

Don't forget to insert your JavaScript code just before the closing body tag. Check out the demo here: jsFiddle

Answer №2

Visit this JSFiddle demo

const colors = ["#FFAABB", "#88CCDD", "#AACCEE", "#77BBAA", "#99DDEE"];
const sizes = ["10", "20", "30", "40", "50"];

for (let j = 0; j < 5; j++) {
    document.getElementById('box' + (j+1)).style.backgroundColor = colors[j];
    document.getElementById('box' + (j+1)).style.width = sizes[j] + 'px';
}

Answer №3

utilizing jquery each function

$('div[id*=element]').each(function(idx,val)

Answer №4

Check out the following code snippet:

let colors = Array("#F00", "#FF0", "#0F0", "#0FF", "#00F");
let widths = Array("20", "40", "60", "80", "100");    
for (let i=0; i<5; i++)
{    
    document.getElementById('div'+(i+1)).style.backgroundColor = colors[i];
    document.getElementById('div'+(i+1)).style.width = widths[i] + "px";
}

Preview: Fiddle

Answer №5

Have you considered using JQuery? It's faster and makes fixing issues quick.

<title>Hello</title>

<body>
        <div id="div1">div1</div>
        <div id="div2">div2</div>
        <div id="div3">div3</div>
        <div id="div4">div4</div>
        <div id="div5">div5</div>
</body>

Here is the JavaScript code:

$(document).ready(function(){

var color = Array("#F00","#FF0","#0F0","#0FF","#00F");
var width = Array("20", "40", "60", "80", "100");

            for (i=1; i<6; i++)
            {
                $("#div" + i ).css("background-color", color[i-1]);
                $("#div" + i).css("width",width[i-1]);                                
            }
});

You can view it on http://jsfiddle.net/C48nd/

Answer №6

 <html>
    <head>
        <title>Hello World</title>

    </head>
    <body>
        <div id="box1">box1</div>
        <div id="box2">box2</div>
        <div id="box3">box3</div>
        <div id="box4">box4</div>
        <div id="box5">box5</div>
    </body>
    <script type="text/javascript">

        var colorArray = Array("#F00","#FF0","#0F0","#0FF","#00F");
        var widthArray = Array("20px", "40px", "60px", "80px", "100px");

        {
            for (j=1; j<5; j++)
            {

                var elementId = "box" + j;
                alert(elementId);
                document.getElementById(elementId).style.background = colorArray[j];
                document.getElementById(elementId).style.width = widthArray[j];
            }
        }

        </script>
</html>

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

What steps are needed to activate the next and previous buttons in the bootstrap carousel?

Recently, I've taken an interest in using Bootstrap 5 for the design of my website. I wanted to incorporate a carousel for showcasing my coffee products, with only 3 items visible at a time when the navigation buttons are clicked. Currently, the caro ...

Transferring information among PHP web pages using a list generated on-the-fly

I am working with a PHP code that dynamically generates a list within a form using data from a database: echo '<form name="List" action="checkList.php" method="post">'; while($rows=mysqli_fetch_array($sql)) { echo "<input type='pas ...

``Is there a way to position an image at the center in Python dash?

Can someone help me with centering an image in my Flask dash app? Here is the code I have: import dash from dash import html, dcc import dash_bootstrap_components as dbc app = dash.Dash(__name__) app.layout = html.Div([ dbc.CardImg(src=r'assets/ ...

The content of my menu is concealed within a DIV. It may remain hidden or malfunction

I am in the process of creating master pages. In one of the master pages, I have implemented a dropdown menu using jQuery and CSS. While it works perfectly fine on some pages, it seems to be hidden on others that contain a div element. This is because the ...

Enabling Android WebView JavaScript to Access Local Files

Currently, I am searching for a sophisticated method to retrieve local files (whether on the phone's memory or SD Card) on an Android device using JavaScript within a WebView. I have loaded this WebView with an HTML page from the device's assets ...

Determining Visibility in Three.js: A Guide to Checking if an Object is in View of the Camera

Struggling to determine the best method for checking if an Object3d is visible to the camera. Imagine a sphere in the center of the screen with cubes randomly placed on its surface. I need a way to identify which cubes are visible (on the front half of th ...

How far is the Google Maps Marker Distance?

I am interested in knowing how I can calculate the distance between my current location and a marker on the map, taking into account the curvature of the earth. Below is my JavaScript code: var map; function initMap(){ //constructor creates a new map - on ...

What is the best way to retrieve all the values of a specific field from a store?

Is there a way to retrieve all the values of a specific field from a store without manually selecting each cell? In my grid, I am looking to extract all the values from a particular column directly from the store. Is this achievable without any manual sel ...

Loading complex models with Three.js

Whenever I attempt to load a significantly large file utilizing the appropriate loaders provided by the library, the tab in which my website is running crashes. Despite trying to implement the Worker class, it doesn't seem to resolve the issue. Here i ...

Why does the col-sm-* class affect the appearance on extra small screens?

For a current project, I have incorporated bootstrap into my design and have set up varying column widths for xs, sm, and md screens. Initially, I utilized col-xs-* and col-md-* to ensure the columns resized appropriately for xs, md, and lg screens. Howeve ...

Achieve a disabled scroll bar feature on Firefox

I am experiencing an issue with a Javascript tabbed dialog where the pages have varying heights. Some of them are larger than the browser window. In Internet Explorer, there is always a scrollbar present on the right side. When it is not needed, it appear ...

Urllib2 retrieves HTML source code from various websites

Seeking assistance with retrieving the HTML code of a specific page using urllib2. The code provided is not giving me the exact HTML as displayed in my browser... Here is my current code: import urllib2 request = urllib2.Request('http://fiverr.com/l ...

Instructions on adding a class to the parent element when the child has a particular class

Here is the html structure I am working with: <section> <div class="v-middle"> <div class="row"> <h5 class="heading">Heading goes here</h5> </div> </div> </section> ...

Bootstrap modal's offset returning blank value

One way to navigate to a specific element within a Bootstrap modal is by checking the offset of that particular element. If there are multiple divs within the modal, each with its own unique id (#row-1, #row-2, etc.), you can open the modal and input the f ...

The value of the comment box with the ID $(CommentBoxId) is not being captured

When a user enters data in the comment box and clicks the corresponding submit button, I am successfully passing id, CompanyId, WorkId, and CommentBoxId to the code behind to update the record. However, I am encountering an issue as I also want to pass the ...

When trying to run the code locally, JS and Bootstrap seem to have trouble functioning together, despite

Check out my codepen project here: https://codepen.io/ldrumsl/pen/ZxdZwa Below is the JavaScript code: $('#datetimepicker1').datetimepicker(); $('#datetimepicker2').datetimepicker(); Downloaded index.html file content: <!DOCTYPE ...

Issue with creating a variable name inside a JavaScript for loop

Here is the code snippet I am currently working on: var var1 = 58; for(var i=0;i<10;i++){ if(("var"+i) == 58) { console.log("they are equal"); } } I am wondering why ("var" + i) is not equal to 58 in this scenario. Could someone please provide an ...

Issues with zoom functionality not functioning properly within IE11

I am currently developing an application with Angular that is designed to be compatible with tablets and touch-enabled devices. One of the key features I want to implement is the ability for users to zoom/scale up the app, especially for those with visual ...

What is the integration of Google URL format with a PHP application?

When it comes to php websites, URLs are commonly written in the form of page.php?id=123 or rewrite moded page/Id/123 However, when looking at google I observed that URLs look more like google.com/search?q=Wordpress I attempted to structure website links ...

What is the most effective method for dynamically creating an HTML report from scratch?

I need help figuring out the best way to convert a substantial amount of program output into an HTML report. Right now, I am manually piecing together the report by extracting relevant information from the extensive logging in my large Python program and f ...