What is the most efficient way to modify this code to be as concise as can be?

Is it possible to condense this code further? I've marked the section within the script tag that I'd like to modify (it's after the for loop). Perhaps using a different approach like a for loop would be better? Or is there an easier way to accomplish this? I'm unsure of what to do next. Let me know if you need more clarification on the main question. Thank you for taking the time to read and assist.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="https://fonts.googleapis.com/css2?family=Clicker+Script&display=swap" rel="stylesheet">

</head>

<body>
    <style>
        body {
            background-image: url('169240.jpg');
            background-size: cover;
            margin: 0;
            padding: 0;
        }

        .p {
            transform: rotate(-90deg);
            -ms-transform: rotate(-90deg);
            -webkit-transform: rotate(-90deg);
            position: absolute;
            color: white;
            font-size: 26px;
            margin-top: 32px;
            margin-left: -33px;
        }
    </style>

    <script >
        var header_div = document.createElement('div')
document.body.appendChild(header_div)
var p = document.createElement('p')
header_div.appendChild(p)
p.innerHTML = 'Meal Diary'
p.style.fontFamily = 'Clicker Script'
p.style.fontSize = '75px'
p.style.marginBlockEnd = '0'
p.style.marginBlockStart = '0'
p.style.marginLeft = innerWidth * 0.4 + 'px'
p.style.color = 'white'
header_div.style.height = '100px'
header_div.style.backgroundColor = '#8C7484'
header_div.style.alignItems = 'center'
header_div.style.paddingTop = '5px'
var main = document.createElement('div')
document.body.appendChild(main)
main.style.width = innerWidth * 0.6 + 'px'
main.style.height = window.screen.height * 0.6 + 'px'
main.style.backgroundColor = '#F2D8CE'
main.style.marginLeft = innerWidth / 5 + 'px'
main.style.marginTop = '35px'
main.style.border = '2px solid #8C7484'
var data = [
    {
        name: 'Breakfast',
        bgcolor: '#F5D7E2',
        headerbg: '#E0AC9F',
        food1: 'Boiled Egg',
        food1_img: 'egg.png',
        food1_calories: 78,
        food2: 'Greek Yogurt',
        food2_img: 'greek_yogurt.png',
        food2_calories: 100,
        food3: 'Oatmeal',
        food3_img: 'oatmeal.png',
        food3_calories: 120,
        food4: 'Chia Seed',
        food4_img: 'egg.png',
        food4_calories: 138,
        food5: 'Nuts',
        food5_img: 'egg.png',
        food5_calories: 172,
        food6: 'Fruit Salad',
        food6_img: 'egg.png',
        food6_calories: 124
    },
    {
        name: 'Lunch',
        bgcolor: '#EDCCE5',
        headerbg: '#8C7785'
    },
    {
        name: 'Snack',
        bgcolor: '#DDC3E0',
        headerbg: '#BF9BAF'
    },
    {
        name: 'Dinner',
        bgcolor: 'rgb(191 171 194 / 73%)',
        headerbg: '#A697A1'
    },
];


for (var i = 0; i < data.length; i++) {
    var element = document.createElement('div');
    element.className = 'card' + i;
    element.style.width = main.style.width
    element.style.height = '115.25px'
    element.style.backgroundColor = data[i].bgcolor;
    main.appendChild(element);
    var header_div1 = document.createElement('div')
    header_div1.style.width = '115.25px'
    header_div1.style.height = '50px'
    header_div1.style.backgroundColor = data[i].headerbg
    var content = data[i].name;
    header_div1.innerHTML = content
    header_div1.className = 'p';
    element.appendChild(header_div1)
    var meal_div = document.createElement('div')
    meal_div.className = 'meal_div' + i;
    meal_div.style.width = '200px'
    meal_div.style.height = '115.25px'
    meal_div.style.backgroundColor = 'pink'
    meal_div.style.marginLeft = '75.6%'
    meal_div.style.display = 'flex'
    meal_div.style.flexDirection = 'row'
    meal_div.style.flexWrap = 'wrap'
    element.appendChild(meal_div)
}
`start`
var meal_div0 = document.getElementsByClassName('meal_div0')
var foodimg0 = document.createElement('img')
foodimg0.src = data[0].food1_img
foodimg0.width = '40'
foodimg0.height = '57.6'
foodimg0.style.margin = '5px'
var foodimg1 = document.createElement('img')
foodimg1.src = data[0].food2_img
foodimg1.width = '50'
foodimg1.height = '57.6'
foodimg1.style.margin = '5px'
var foodimg2 = document.createElement('img')
foodimg2.src = data[0].food3_img
foodimg2.width = '50'
foodimg2.height = '57.6'
foodimg2.style.margin = '5px'
var foodimg3 = document.createElement('img')
foodimg3.src = data[0].food4_img
foodimg3.width = '50'
foodimg3.height = '57.6'
foodimg3.style.margin = '5px'
var foodimg4 = document.createElement('img')
foodimg4.src = data[0].food5_img
foodimg4.width = '50'
foodimg4.height = '57.6'
foodimg4.style.margin = '5px'
var foodimg5 = document.createElement('img')
foodimg5.src = data[0].food6_img
foodimg5.width = '50'
foodimg5.height = '57.6'
foodimg5.style.margin = '5px'
meal_div0[0].appendChild(foodimg0)
meal_div0[0].appendChild(foodimg1)
meal_div0[0].appendChild(foodimg2)
meal_div0[0].appendChild(foodimg3)
meal_div0[0].appendChild(foodimg4)
meal_div0[0].appendChild(foodimg5)


`end`


    </script>

</body>

</html>

Answer №1

You can streamline your code by creating a helper function to handle repetitive tasks, and then simply calling it for each item.

function createFoodImg(src, w, h, margin) {
    var foodImg = document.createElement("img");
    foodImg.src = src;
    foodImg.width = w;
    foodImg.height = h;
    foodImg.style.margin = margin;
    return foodImg;
}
meal_div0[0].appendChild(createFoodImg(data[0].food1_img, "40", "57.6", "5px"))
meal_div0[0].appendChild(createFoodImg(data[0].food2_img, "50", "57.6", "5px"))
//repeat the process for other items

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 is the proper way to ensure a pull right display appears correctly?

This is the code I am currently using .tag-container.bottom-border.col-middle h1.text-center {{ tag.name }} button.btn.btn-follow.pull-right(ng-hide="hasFollowed" ng-click="tagArticles.followTag()") Follow I am trying to align the tag name in th ...

developing an array within JavaScript

Can someone clarify if the following code snippet creates an empty array in JavaScript: var arr = {}; Is it equivalent to using the new Array() constructor like this: var arr = new Array(); I would appreciate any insights on this matter. Thank you! ...

Enforce the text inside the child div to perfectly fit within the parent container

I have a challenge with two div elements in my HTML code as shown below: <div id="parent"> <div id="child"> <p class="child-text"> ..... </p> <a class="child-link"> ..... </a> <p class="ch ...

Ensure that the Div element is able to wrap lines in the same way that the Span element

Is there a method to ensure that a div element wraps the lines similar to how a span does? JSFiddle for testing In this example, I utilized the span tag to create an appearance as if the text was highlighted by a yellow highlighter pen. Everything functi ...

A CSS class that inherits properties from another class

I have a simple question that I can't seem to find any documentation on the internet for. It's possible that my search terms were not quite right... Let's consider a CSS class called centered, which centers elements and performs other actio ...

Tips on scrolling down to find the text you're looking for

I attempted to scroll downwards in my application's window using the following JavaScript code: ((JavascriptExecutor) driver).executeScript("windows.scrollBy(0,500)"); Additionally, I tried to ensure a specific element is in view with this script: ...

How can I incorporate a counter into my ng-repeat loop in Angular?

Do you know where I can find documentation on adding a numbered count to each item returned by an ng-repeat in Angular? This is not like assigning an Id, but more like, if 4 items are returned, each JSON object could include a number before the data. Her ...

Is there a way to relocate the collapse button to the bottom after it has been clicked?

I have been using Bootstrap to design a expandable card that can be expanded when clicked. I am currently using the collapse feature, but I am facing an issue where the button remains in its original position, whereas I want it to move to the bottom of the ...

Ways to organize the HTML layout for centering content within a div

Returning to html can be tricky...I often forget the basics. I'm trying to center the spans inside this div. Not sure if my structure is correct, any suggestions are welcome! Check out this jsfiddle link for reference .define_link { b ...

Traversing a JavaScript class within a for loop

I am attempting to access the locations listed in json.responseJSON.Sites, starting with LHR on the first iteration and then NJE on the next one, and so forth. The notifications for each location are "LHR" and "NJE", respectively. Is it possible to achieve ...

What is the best way to determine the number of lines within a textarea?

My goal is to accurately calculate the number of lines in a textarea, like so: line 1 line 2 line 3 line 4 which should equal 4 lines. Essentially, pressing enter once should create a new line. Unfortunately, the following code is not achieving this: v ...

Can a Vue component be designed to have one required prop out of several options?

I am currently developing a Vue component that is required to accept either text input or a link. When a link is provided, an anchor tag needs to be created and when text is inputted, a span should be generated. The issue I am facing is that it seems each ...

JavaScript: How to Build a Digital Grocery List with Browser Storage

Struggling with a tough exercise question, I could use some help deciphering it. https://i.stack.imgur.com/V5he2.png Here is how I've started the code: <!DOCTYPE html> <html> <head> <title></title> <script> fun ...

Is my approach to using the linear-gradient hack for colored images incorrect?

Recently stumbled upon a tutorial on achieving this effect at https://css-tricks.com/tinted-images-multiple-backgrounds/ /* Method I attempted */ .tinted-image { background: /* top, transparent red, simulated with gradient */ linear-gradient( ...

Error encountered while attempting to upload file via POST request due to a failed NodeJS fetch operation, with the specific issue being

I am attempting to upload a file using the native fetch function in NodeJS version 17.5 (which can be found at https://nodejs.org/ko/blog/release/v17.5.0/). Unfortunately, I am encountering the following error: TypeError: fetch failed at Object.processRes ...

Retrieving information with C# Post using JavaScript

I'm trying to retrieve the resulting string from the function resultado2() located at the following link: Initially, I wrote the following code: string url = "http://barion.inapi.cl/BuscaBiblio/inicio.php"; Uri uri = new Uri(url); HttpWebRequest re ...

How can CSS grid be utilized to create columns of various widths that wrap onto a new line

Struggling with CSS grid in my new responsive design, particularly regarding wrapping. The issue is with a nav bar containing a header that needs to be aligned left and four buttons that should be aligned right. Currently, using: grid-template-columns: r ...

Arrangement of pipe operators in RXJS Angular 5

Do you think my operators are in the correct order? The code snippet below shows that the console logs from the two taps display the same values. Something seems off, right? return this.pcs.getAvailableMaterials(currentProduct.id).pipe( map( ...

Is it possible to receive a unique value error even when providing the correct key value in a map?

I encountered an issue while using a map function with an array in my application. Even though I have provided a unique key, Google Chrome console is still showing an error related to the unique key. Error Each child in a list should have a unique "ke ...

Techniques for transferring child properties and values to parent components upon the screen being initialized

Is there a way to pass property values from a child component to a parent component when the react app is first loaded? In my scenario, I have a parent component named app.js that renders a home component containing a JSON component. Initially, upon loadi ...