Modifying CSS classes using conditional statements and loops

 var first_left = ['Photo', 'Info', 'Question 1', 'Question 2', 'Question 3', 'Question 4', 'Question 5'];

var names = ['Abuela', 'Abuelo', 'Oma'];

function display() {
    for (var y = 0; y & lt; names.length; y++) {
        var rc = document.getElementById('firstR');
        var div1 = $("& lt; div > & lt; /div > ");
        var div2 = $("& lt; div > & lt; /div > ");
        div2.addClass(names[y]);
        $(rc).append(div1);
        $(rc).append(div2);
        $(div1).css("border", "0px solid green");
        $(div2).css("border", "5px solid black");
        $(div1).css("height", "80px");
        $(div1).css("margin-top", "3em");
        $(div2).css("height", "380px");
        $(div2).css("margin-top", "3em");
        $(div2).css("margin-bottom", "12em");
        var h = $("& lt; h1 > & lt; /h1 > ");
        $(h).html(names[y]);
        $(h).css("font-size", "60px");
        $(h).css("margin", "auto");
        $(h).css("text-align", "center");
        $(div1).append(h);

        for (var z = 0; z & lt; first_left.length; z++) {
            var lc = document.getElementById('firstL');
            var div = document.createElement('div');
            div.className = first_left[z];
            var p = document.createElement('p');
            p.innerHTML = first_left[z];
            div.appendChild(p);
            lc.appendChild(div);
            p.style.margin = 'auto';
            p.style['font-size'] = '25px';
            p.style['text-align'] = 'center';
            div.style.border = '0px solid black';
            div.style.height = '40px';
            div.style.width = '120px';
            div.style['margin-top'] = '3em';
            if (z == 6) {
                div.style['margin-bottom'] = '10em';
            }
            div.style['background-color'] = 'deepskyblue';
            div.style['grid-row'] = [z + 1] + '/' + [z + 2];
            div.style.transition = "transform .5s";
            div.style['border-radius'] = '10px';
            $(div).hover(function () {
                $(this).css({
                    transform: 'scale(1.3)'
                });
            }, function () {
                $(this).css({
                    transform: 'scale(1)'
                })
            });
            if (y == 0 & amp; & amp; z == 0) {
                div.onclick = function() {
                    $("." + names[0]).css("backgroundImage", "url('abuelos/oma.jpg')");
                    $("." + names[0]).css("backgroundSize", "550px 500px");
                }
            };
            if (y == 1 & amp; & amp; z == 0) {
                div.onclick = function() {
                    $(div2).css("backgroundImage", "url('abuelos/gma.jpg')");
                    $(div2).css("backgroundSize", "cover");
                }
            }
        }
    };
};

display(); 
 .whole {
    display: flex;
    justify-content: space-between;
}

.left {
    display: grid;
    width: 100%;
    grid-template-columns: 1fr 1fr 1fr;
    grid-template-rows: 80px 80px 80px 80px 80px 80px 80px;
}

.left_column {
    grid-column: 2/3;
}

.right_column {
    width: 100%;
    height: 560px;
    margin-right: 3em;
} 
 <!DOCTYPE html >
<html lang = "en" >
<head>
<meta charset="UTF-8">
<title>Home Page | Roctober92.net</title>
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" type="text/css" href="abuelos.css">
</head>
<body>
<main>
<div class="whole" id="one">
<div class="left">
<div class="left_column" id="firstL">
</div>
</div>
<div class="right_column" id="firstR">
</div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="abuelos.js"></script>
</main>
</body>
</html> 

My goal:

  1. Create a DIV for each item in the list using a for-loop
  2. Add a class to each DIV with a specific name == list[y]
  3. Include another for-loop inside with different list items(z)
  4. If y == (a number) and z == (a number), adjust the CSS of a unique class

THE ISSUE: It only functions correctly if I reference the element as $(div2), which modifies the last div2 I append instead of a specific one. I would prefer it to edit the first div2 I append (with names[0] as the class name). However, it doesn't recognize it. As you press 'Photo' alongside the first box in the code snippet, a picture should appear in the box.

Answer №1

It's important to note that class names cannot have spaces. To work around this, consider substituting the space with another character like an underscore when utilizing it as a class.

    div2.addClass(names[y].replace(/\s/g, ' ');
    
    $("." + names[0].replace(/\s/g, ' ')).css("backgroundImage", "url('abuelos/oma.jpg')");

Answer №2

I am grateful to Barmar for the guidance that led to these successful changes.

$(names[0])  -->  $("." + (names[0]))

// It is important to note that classes cannot have spaces: 
div2.addClass(names[y]); //--> 
div2.addClass(first_left[y] + "a");

// The items within first_left do not contain spaces

$("." + first_left[0] + "a");

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

Tips for duplicating specific div elements

Is there a way to create copies of selected divs within the same panel using a Javascript report designer? I attempted to achieve this by using the following code snippet: function DesignerClone() { $(".ui-selected").each(function () { va ...

Steps to transfer a JavaScript variable to a PHP session

Currently, I am in the process of retrieving the value of a checkbox and assigning it to a PHP session variable. Below is the relevant portion of the code: The checkbox: $html .= '<span><input type="checkbox" id="checkbox' ...

Using the <noscript> tag for an individual element or a comparable alternative

So, I have a link labeled "Impressum" that when clicked, opens up the Impressum section. <a data-open="something">Impressum</a> <div class="reveal" id="something" data-reveal> <img src="images/reverseLogo.png"> <h1>Imp ...

ESLint detected a promise being returned in a function argument where a void return type was expected

I'm encountering a recurring error whenever I run my ESLint script on multiple routers in my server. The specific error message is as follows: error Promise returned in function argument where a void return was expected @typescript-eslint/no-misuse ...

Leveraging em units in jQuery Script

I'm currently in the process of building a website and I'm facing an issue with converting measurements to em's. The script that I have reused from a previous project only seems to work with pixels, despite my efforts to make it compatible w ...

What is the best way to create a "select all" check box in HTML and display the selected values in a div?

$(function () { //This function selects all checkboxes and unchecks selectall if any checkbox is not checked. var checkall = $('#checkall'); var boxes = $('input[type="checkbox"]').not(checkall); checkall.click(function ...

Using jQuery and JSON data to dynamically populate a second dropdown menu with filtered options

I am working on a form with two drop-down menus and a text box. The first drop-down contains static values, while the second drop-down is populated dynamically from a JSON array. My goal is to filter the options in the second drop-down based on the selecti ...

What could be causing my BXSlider to malfunction?

Issue My BXSlider is not showing up on the page. It just displays a blank page. I have double-checked my page structure and everything seems to be in order. Expected Appearance HTML Code <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ...

Looking for assistance with a Vue.js BMI Calculator project

Currently, I am delving into Web Development using Vue. As part of my project, I have constructed a component that calculates the BMI (Body Mass Index) of an individual. To collect the necessary data, I have implemented a form utilizing bootstrap-vue. Howe ...

Retrieve the value of a variable by using either an HTTP GET or POST request

Here's the HTML code snippet that I'm working with: <head> <h1>Sample Page</h1> </head> <body> <form method="POST" action=""> Enter Keyword <input type="text" name="key"> ...

The selector bar in Cypress does not work properly when trying to find the text 'foo' using jQuery

Having trouble with jQuery selectors in my Cypress tests. I often need to use jQuery selectors to locate elements based on text or unique generated numbers instead of using cy.contains(). Any help would be greatly appreciated! https://i.sstatic.net/FjqzJ ...

Executing a JavaScript function to trigger a PHP script that saves data into a MySQL database

I have a button in my HTML file that, when clicked, should insert data into a database and then reload the page. I am calling a JavaScript function within the onclick event to handle this. Below is the JavaScript function: function grandFinale() { i ...

Could we incorporate a backwards typewriter animation?

Is there a way to delay this animation for 2 seconds before playing in reverse? I came across this online and made some edits, but I'm still new to this (early stages). Can this be achieved using CSS, HTML, and JavaScript? I plan to use this as an ale ...

A guide on retrieving a JSON static file that has been imported using Webpack

I have a JSON static file named someFile.json within my project directory. This JSON file contains a stringified array of objects: [{...},{...},etc] To import it using Webpack (version 4.41.2), I use the following line in my App.js file: import '.. ...

What is the process for running a continuous stream listener in a node.js function?

I am currently working with a file called stream.ts: require('envkey') import Twitter from 'twitter-lite'; const mainFn = async () => { const client = new Twitter({ consumer_key: process.env['TWITTER_CONSUMER_KEY'], ...

Exploring the components of the scene with three.js

I have a desire to explore each element within a particular scene. These elements come in various forms such as THREE.Object3D, THREE.Mesh, and more. Some of these elements contain a property called children, which is essentially an array of other elements ...

The function documents.getElementsById() is hindering the effectiveness of Javascript validation

I'm facing an issue with this code. If I uncomment the specific line, the form bypasses validation and goes directly to the linked page in the action attribute. However, if I keep it commented out, the validation runs smoothly, and the alert box displ ...

Leveraging the Power of CSS in Your Express Applications

Struggling to make my CSS links functional while working on localhost. Currently, when I view Index.html on my server, it displays as plain text without any styling. Even after trying the express middleware, the CSS files are still not being served, result ...

Using JavaScript to send form input in the form of a 2D array through AJAX

I am currently working on a form that looks like this: <form name="chat" id="chat" action="" onsubmit="sendMessage()"> <a name="chat">&nbsp;</a> <input type="text" name="chat" id="chat" size="38" maxlength="50" vertical-align="m ...

Prevent background music from being manipulated

I've implemented an audio HTML element with background music for a game: <audio class="music" src="..." loop></audio> However, I have encountered an issue where upon loading the page, I am able to control the music usi ...