Tips for updating CSS styles for multiple innerHTML elements using a JavaScript for loop

<div id="test"></div>
<script type="text/javascript">

window.names=["jin kazama", "nina williams"];
window.values=[25, 37];
len=names.length
for (var i = 0; i < len; i++)
{
    document.getElementById('test').innerHTML+= names[i];
    //names[i].css=margin-left: values[i]px;//   /* Pseudo-code attempt to move elements over different amounts */

}

</script>

This is my goal. The for loop functions correctly except when attempting to move each element a varying amount in the innerHTML. For example, moving 'jin kazama' over by 25px and 'nina williams' over by 37px. How can this be achieved without error?

Answer №1

Consider the following approach:

// Define variables within the local scope:
var names=["heihachi", "forest law"],
    values=[22, 31],
// Get a reference to the element outside of the loop (once, not multiple times):
    test = document.getElementById('test'),
// Create a new span element for wrapping text:
    span = document.createElement('span'),
// Declare a variable for working with the node:
    _temp;

// Ensure 'position: relative' to move elements/words around:
span.style.position = 'relative';

// Iterate over the names array:
for (var i = 0, len = names.length; i < len; i++)
{
    // Work on a clone of the 'span':
    _temp = span.cloneNode();
    // Append a child textNode to the cloned node:
    _temp.appendChild(document.createTextNode(names[i]));
    // Set the left property of the node's style object:
    _temp.style.left = values[i] + 'px';
    // Append the node to the 'test' node:
    test.appendChild(_temp);    
}

JS Fiddle demo.

Alternatively, you can create an array of objects, each containing a name and value property:

var namesAndPositions = [{
    'name' : 'heihachi',
    'value' : 22
},{
    'name' : 'forest law',
    'value' : 31
}],
    test = document.getElementById('test'),
    span = document.createElement('span'),
    _temp;

span.style.position = 'relative';

for (var i = 0, len = namesAndPositions.length; i < len; i++)
{
    _temp = span.cloneNode();
    _temp.appendChild(document.createTextNode(namesAndPositions[i].name));
    _temp.style.left = namesAndPositions[i].value + 'px';
    test.appendChild(_temp);
}

JS Fiddle demo.

To achieve the measurement (22px and 31px to the left of each element), use display: inline-block and set marginLeft:

// Code above remains unchanged

span.style.display = 'inline-block';

for (var i = 0, len = namesAndPositions.length; i < len; i++)
{
    _temp = span.cloneNode();
    _temp.appendChild(document.createTextNode(namesAndPositions[i].name));
    _temp.style.marginLeft = namesAndPositions[i].value + 'px';
    test.appendChild(_temp);
}

JS Fiddle demo.

References:

Answer №2

Let's illustrate a simpler example:

window.heroes=["Spider-Man", "Black Widow"];
window.powers=[12, 15];
var count=heroes.length;

var display = document.getElementById('display');
for (var j = 0; j < count; j++)
{
    var item = document.createElement("span")
    item.innerHTML = heroes[j];
    item.style.marginLeft = powers[j] + 'px';
    display.appendChild(item);
}

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

Stacked on top of one another are in-line block items

I've been working on this code for a while now, but I can't seem to get it right. My goal is to create a horizontal line of navigation links with the first link aligned to the left and the rest following in sequence like a text line. However, a ...

Only enable the last day of each month on the React Material UI date picker, all other dates in the year should be disabled

I've been struggling to find a solution that allows users to only choose the last day of each month in a year, disabling all other days. After searching for answers using the Material UI date picker, I have not been successful. If anyone can guide me ...

Receiving a k6 response that includes a JSON object with a lengthy integer value

During a performance test, I encountered an issue where the response contained items like: {"item":{"id":2733382000000000049}} When parsed using k6's response.json(), it appeared as : {"item":{"id":273338200000 ...

Changing the information of objects stored in arrays using React Three Fiber

My challenge is with an array of roundedBox geometry shapes called myShape. I am trying to figure out if it's possible to change the position of one of the shapes within the array without creating a new shape altogether. Ideally, I would like to updat ...

Why does the "revalidate" field in Incremental Static Regeneration keep refreshing without considering the specified delay?

I am currently referencing the guidance provided at: https://nextjs.org/docs/basic-features/data-fetching/incremental-static-regeneration. My intention when setting the revalidate: 60 * 10 parameter is: To have the content remain consistent for at least ...

What is the best way to update the div id by extracting the last digits from a number?

Is there a way to change the div ids using a function? Before: <div id="a_1">a1</div> <div id="b_1">b1</div> <div id="c_1">c1</div> <div id="d_1">d1</div> <button onclick="change()">Change</button& ...

Executing Datalist's Delete Command through Page Methods Implementation

Recently, I came across an issue with my DataList and Update Panel on my webpage. I noticed a significant delay in response time after incorporating the Update panels... intrigued, I delved deeper into this phenomenon and found some interesting insights in ...

The divs with the specified class are not applying the desired styles to my document. However, the input and labels are functioning correctly. What could I be overlooking?

Web Development : <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title> The Coding Academy Survey</title> <link rel="stylesheet" href="styles.css" ...

Error encountered at /edit-menu/edit/: The 'Product' object does not contain the attribute 'is_valid'

I am attempting to extract all product names from the Product model, display them along with their prices on the screen, and enable users to modify the price of any item. Although I have managed to list them out and provide an input field for the price, I ...

Trouble arises when rendering nested components in React Router 4

My issue lies with implementing React Router 4 while utilizing "nested" routes. The problem arises when one of the top routes renders a component that matches the route, even though I do not want it to be rendered. Let me provide the relevant code snippets ...

Trouble updating Kendo DropDown in Internet Explorer

Having an issue with updating a Kendo DropDownList through a javascript function. It works fine in FireFox and Chrome, but not in Internet Explorer. @(Html.Kendo().DropDownList() .Name("myDDL") .HtmlAttributes(new { style = "width: 320px" }) . ...

Increment and Decrement Values with JQuery

I am looking to implement a client-side Plus/Minus system where users can click on the plus sign to increase a value by 1 and minus sign to decrease the value by 1. The value should not go below zero and it should initially start at 0. Is there a simple wa ...

In JavaScript, what is the best way to target the initial option element in HTML?

As a newcomer to javascript, I'm wondering how to target the first option in the HTML <option value="">Choose an image...</option> without altering the HTML itself? My thought is: memeForm.getElementById('meme-image').getElement ...

javascript monitoring numerous socket channels for echoes

Currently, I am in the process of developing a chat application. On the server side, I am utilizing: php, laravel 5.4, and pusher. On the client side, I have incorporated vue.js along with laravel-echo. Initially, I successfully created a "public chat roo ...

JQuery table sorter is unable to effectively sort tables with date range strings

I am facing an issue with sorting a column in my table that contains text with varying dates. The text format is as follows: Requested Statement 7/1/2014 - 9/16/2014 When using tablesorter, the sorting does not work properly for this column. You can see ...

The path mappings specified in the tsconfig.json file are not resolving correctly during the

Everything runs smoothly with my imports during coding, but after building the project using tsc, the imported files are not resolving to valid paths. This is how my tsconfig.json looks: { "compilerOptions": { "target": "ES2 ...

What is the simplest way to extract only the error message?

Having this code snippet. $('div#create_result').text(XMLHttpRequest.responseText); If we look at the content of XMLHttpRequest, it shows: responseText: Content-Type: application/json; charset=utf-8 {"error" : "User sdf doesn't exist"} st ...

Steps to define a JavaScript mixin in VueJS

Currently, I am working on a Vue project with TypeScript and in need of using a mixin from a third-party library written in JavaScript. How can I create a .d.ts file to help TypeScript recognize the functions defined in the mixin? I have attempted the fol ...

Node.js Promise Rejection: TypeError - Unable to access property 'sign' because it is undefined

tran_script.js const CoinStack = require('coinstack-sdk-js'); const coinstackClient = new CoinStack('YOUR_COINSTACK_ACCESS_KEY', 'YOUR_COINSTACK_SECRET_KEY'); // Actual keys not displayed const privateKeyWIF = CoinStack.ECK ...

Trouble with downloading files using the anchor (a) tag in React

Every time I try to click on the a tag to download the file named approved_leads.zip, I keep receiving an error message saying "failed - no file". It seems like the path is correct, so I'm not sure what is causing the issue. <a href="../../ass ...