Utilizing CSS for styling a class with a dynamic name

On the server side, I am dynamically generating class names like this:

<p class="level_1">List item 1</p>
<p class="level_2">List item 2</p>
<p class="level_3">List item 3</p>
<p class="level_1">List item 1</p>
<p class="level_2">List item 2</p>
<p class="level_1">List item 1</p>

I want the output to have indentation that looks like this:

List item 1
   List item 2
      List item 3
List item 1
   List item 2
List item 1

The class name syntax is level_$i, where $i is a variable that can range from 1 to any level. How can I apply CSS to create this indentation in this scenario?

Answer №1

CSS doesn't support for loops, but you can use LESS instead. Check out this tutorial on LESS Loops

If you want to achieve the same effect with jQuery, take a look at this jsFiddle example I put together for you.

var i = 1,
    val = 0;

$('[class^=level_]').each(function(){

$('.level_' + i).css('padding-left',val+'px');
    i++;
    val += 20;
});

Answer №2

There are two possible solutions that I can suggest:

  1. One option is to automatically generate CSS styles as you create the list using PHP
  2. Another alternative is to utilize JavaScript/jQuery to parse elements and dynamically create the necessary rules. You can check out an example on JSBin: http://jsbin.com/zaviqeyavico/1/edit

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

Angular's NgShoppingCart is designed in such a way that items stored in the localStorage are automatically cleared out

I am currently working on an Angular project using version 8.0.0. To integrate a shopping cart feature into my Angular project, I decided to incorporate the NgShoppingCart library by following the instructions provided here. After adding the library in m ...

Having trouble dividing an HTML file?

Currently, I am working on creating a very basic web page that is divided into two parts. Each part will have its own HTML file: Welcome.html & Welcome.css: <html> <head> <link rel="stylesheet" type="text/css" href="Welcom ...

Determine the character's position in an input field by tracking mouse movements

I am in need of a way to determine the position of a character in an input field based on mouse movement. For example, if the input field contains the value 'abcde' and I hover my mouse over the character 'a', the position should be ...

Attempting to initiate an AJAX request to an API

Hey everyone, I've been working on making an AJAX API call to Giphy but I keep receiving 'undefined' as a response. Can anyone offer some advice on how to troubleshoot and fix this issue? Thanks in advance for your help! var topics = ["Drak ...

SignalR enables the display of identical dashboard data pulled from queries on various browsers. By utilizing SignalR/hub, MVC, and C#.NET, the data can

Encountering an issue with my signalr/hub while fetching dashboard data. I'm using 2 browsers to access data based on dates. However, when searching for July on browser 1 and then switching to another month on browser 2, the data in browser 1 gets upd ...

In the Bootstrap multiselect feature, users will be able to choose whether to display an image or selected text

Is there any way to display an image by default instead of options? Code: <select id="example-post" style="width:120px;!important;" class="footerSelect" name="multiselect[]" multiple="multiple"> <opti ...

Vue.js: Issue with dynamically calculating class property

I am attempting to create a computed class in vue.js 2.0 using the following syntax: <li :class="'str1' calcStarClass(1, p.rtg)"> </li> In my methods section, I have the foll ...

What purpose does this particular express variable serve?

I am currently diving into the world of JavaScript, with a basic programming background to boot. However, I have always stumbled when it comes to grasping OOPs concepts. For instance, we start by importing what I believe is the express module through &apo ...

Navigating the issue of updateMany not functioning properly in mongoose and nodejs

I need assistance with updating the author name of a post whenever the user updates their profile name. My code is as follows: router('/:id', async (req, res) { if (req.body._id == req.params.id) { try { const user = await ...

The initial click may not gather all the information, but the subsequent click will capture all necessary data

Issue with button logging on second click instead of first, skipping object iteration function. I attempted using promises and async await on functions to solve this issue, but without success. // Button Code const btn = document.querySelector("button") ...

Seeking out a particular key within a JSON object and then finding a match based on the id within that key's array - how can it be

Recently, I've been exploring JavaScript and encountering challenges when trying to apply array methods on objects. For instance, I received a fetch response and my goal is to extract the 'entries' key and then utilize the native Array.find( ...

Exploring the Integration of Google Maps and Angular Google Places in Angular 2

On my webpage, I am utilizing two components simultaneously: and angular2-google-map-auto-complete from https://www.npmjs.com/package/angular2-google-map-auto-complete. To set the Angular maps key, I have defined it as follows: AgmCoreModule.forRoot({ a ...

Confusion arises from conflicting Vue component script indentation guidelines

As I work on setting ESLint rules for my new Vue project, I am extending both eslint-plugin-vue and airbnb. All is well except for one issue - the indentation of the tag inside Vue components. The usual accepted format looks like this: <script> ex ...

Utilize JavaScript libraries in a TypeScript project

Looking to integrate a payment system called iyzico into my project. The iyzico payment library can be found here. However, there are no types available for it. How can I utilize this library in my Node.js TypeScript Express backend project? I attempted t ...

How can I configure a unique error log format in Winston?

I am facing an issue with the default error log format in Winston, as it includes too much unnecessary information such as date,process,memoryUsage,os,trace. How can I remove these unwanted details from the log? logging.js const express = require('e ...

The retrieval of data from AWS Dynamodb in Node.js is not done synchronously

I recently started working with Node.js and DynamoDB. I created a Node.js SDK to retrieve a single row from a DynamoDB table. The data is being fetched correctly, but there is a delay which is causing an error. Below is a snippet of my code: var AWS = re ...

Ensuring the next tab is not accessible until all fields in the current tab are filled

I am working on a form with a series of questions displayed one at a time, like a slide show. I need help with preventing the user from moving to the next set of questions if there is an empty field in the current set. Below is the script I am using to nav ...

Do not apply styling to a particular page in CSS and HTML

Utilize the teachable.com platform and take advantage of their code Snippets feature (refer to attached photo #1) https://i.stack.imgur.com/dW1lB.png I inserted the following code: div { direction: rtl; } To modify the website's direction to be ...

Tips for focusing on a background image without being distracted by its child elements

I am trying to create a zoom effect on the background-image with an animation but I am encountering issues where all child elements are also animated and zoomed. When hovering over the element, I want only the background part to be animated and zoomed, and ...

Storing Data Property Value from an Item in Rendered List Using Vue: A Quick Guide

I'm currently working on implementing a follow button for list items in Vue. My approach involves extracting the value of a specific property from a list item and storing it in the data object. Then, I plan to utilize this value within a method to app ...