Give a style attribute to every other child element within a class. Each class should function independently, including their final child which contains an if statement

UPDATE: I kindly request a review of the answers provided. Utilizing JavaScript for this task may not be the most efficient method. I will keep this question as it is, as it could potentially benefit someone else.

The aim is for every ".ulInCollapse li" to be independently calculated. My objective is met by assigning different class (or id) names like .ulInCollapse1, .ulInCollapse2, etc., but I understand this is not the best practice. I also made adjustments to my JavaScript code in an attempt to iterate through;

const ulInCollapse = document.querySelectorAll(".ulInCollapse");
console.log(ulInCollapse)
ulInCollapse.forEach(function (ulInCollapse) {
  var ulInCollapseLiCount = ulInCollapse.length;
  var ulInCollapseLiCountChild = document.querySelector(".ulInCollapse li:last-child");
  if (ulInCollapseLiCount % 2 != 0) {
    ulInCollapseLiCountChild.style.paddingTop = "15px";
  } else {
    ulInCollapseLiCountChild.style.paddingTop = "0px";
  }});

I am struggling to determine what steps to take next. I hope I have sufficiently conveyed my issue.

// Targeting all ".ulInCollapse li" and applying conditional statement to adjust padding for the last child accordingly
const ulInCollapse = document.querySelectorAll(".ulInCollapse li");
var ulInCollapseLiCount = ulInCollapse.length;
var ulInCollapseLiCountChild = document.querySelector(".ulInCollapse li:last-child");
console.log(ulInCollapseLiCount);
if (ulInCollapseLiCount % 2 != 0) {
  ulInCollapseLiCountChild.style.paddingTop = "15px";
} else {
  ulInCollapseLiCountChild.style.paddingTop = "0px";

}
/* Here I aim to add padding to every 2nd list item starting from the first */
.ulInCollapse li:nth-child(2n+1):not(:last-child) {
    padding: 15px 0px;
}

/* Applying JS to set padding-top on this selector */
.ulInCollapse li:last-child {
    padding-top: 0px;
}
<button class="collapsible">Simple Tenses</button>
<div class="content">
  <ul class="ulInCollapse" style="list-style-type: none; padding: 0%;">
    <li><a href="#">Simple Present Tense</a></li>
    <li><a href="#">Simple Perfect Tense</a></li>
    <li><a href="#">Simple Perfect Tense</a></li>
  </ul>

</div>
<button class="collapsible">Past Tenses</button>
<div class="content">
  <ul class="ulInCollapse" style="list-style-type: none; padding: 0%;">
    <li><a href="#">Simple Present Tense</a></li>
    <li><a href="#">Simple Perfect Tense</a></li>
    <li><a href="#">Simple Perfect Tense</a></li>
  </ul>
</div>
<button class="collapsible">Future Tenses</button>
<div class="content">
  <ul class="ulInCollapse" style="list-style-type: none; padding: 0%;">
    <li><a href="#">Simple Present Tense</a></li>
    <li><a href="#">Simple Perfect Tense</a></li>
    <li><a href="#">Simple Perfect Tense</a></li>
  </ul>
</div>

Answer №1

Perhaps you were wondering about how to appropriately adjust the padding of the final list item in each list within the document using javascript.

This solution should work, but there might be a more elegant approach than directly setting the padding in this manner. Exploring different styling techniques could lead to a better outcome.

I focused solely on the javascript aspect of your code and added a red left border and an outline in the CSS rule to visually confirm that the correct padding is being applied.

const ulInCollapse = document.querySelectorAll(".ulInCollapse");

//for each .ulInCollapse
ulInCollapse.forEach( ul => {
  //the number of li elements contained in the current ul
  const liCount = ul.querySelectorAll(':scope > li')?.length;
  //15px if liCount is odd, otherwise 0
  const padding = (liCount % 2 !== 0) ? '15px' : '0';
  //sets the the padding-top of the last li in this ul
  ul.querySelector(':scope > li:last-child').style.paddingTop = padding;
})
/* here I am trying to add padding to every 2 li starting from the first */
.ulInCollapse li:nth-child(2n+1):not(:last-child) {
    padding: 15px 0px;
    border-left: solid red;
}

/* I am using js to add padding-top in this selector */
.ulInCollapse li:last-child {
    padding-top: 0px;
}

li {
  outline: solid;
}
<button class="collapsible">Basit Zamanlar (The
      Simple Tenses)</button>
    <div class="content">
      <ul class="ulInCollapse" style="list-style-type: none; padding: 0%;">
        <!-- question: add padding to every two element, how??? -->
        <li><a href="#">Simple Present Tense</a></li>
        <li><a href="#">Simple Perfect Tense</a></li>
        <li><a href="#">Simple Perfect Tense</a></li>
      </ul>

    </div>
    <button class="collapsible">Geçmiş Zamanalar (The Past Tenses)</button>
    <div class="content">
      <ul class="ulInCollapse" style="list-style-type: none; padding: 0%;">
        <!-- question: add padding to every two element, how??? -->
        <li><a href="#">Simple Present Tense</a></li>
        <li><a href="#">Simple Perfect Tense</a></li>
        <li><a href="#">Simple Perfect Tense</a></li>
      </ul>
    </div>
    <button class="collapsible">Gelecek Zamanlar (The Future Tenses)</button>
    <div class="content">
      <ul class="ulInCollapse" style="list-style-type: none; padding: 0%;">
        <!-- question: add padding to every two element, how??? -->
        <li><a href="#">Simple Present Tense</a></li>
        <li><a href="#">Simple Perfect Tense</a></li>
        <li><a href="#">Simple Perfect Tense</a></li>
      </ul>
    </div>

This alternative method provides a more effective way to style elements within a flex container. By utilizing gap for spacing between elements and specifying margin: 10em 0 for spacing between sibling items, the layout can be correctly set without relying on padding which is meant for internal spacing, not external space.

Simply applying the following CSS will handle the layout of items within the container:

.ulInCollapse {
  display: flex;
  flex-direction: column;
  gap: 14px;    
  margin: 10px 0;
}

.ulInCollapse {
  list-style-type: none;
  margin: 0;
  padding: 0;
  
  display: flex;
  flex-direction: column;
  gap: 14px;    
  margin: 10px 0;
}

ul.ulInCollapse li {
  /*
    !!!!
    again this border is to highlight the elegance of this solution
    if you will set the borders to your solution that used paddings you'll see incongruent sizing
  */
  border: solid 1px;
}

ul.ulInCollapse li a {
  color: rgb(0, 132, 255);
  font-size: large;
  text-decoration: none;
}
<button class="collapsible">Basit Zamanlar (The Simple Tenses)</button>
<div class="content">
  <ul class="ulInCollapse" style="list-style-type: none; padding: 0%;">
    <li><a href="#">Simple Present Tense</a></li>
    <li><a href="#">Simple Perfect Tense</a></li>
    <li><a href="#">Simple Perfect Tense</a></li>
  </ul>
</div>

<button class="collapsible">Geçmiş Zamanalar (The Past Tenses)</button>
<div class="content">
  <ul class="ulInCollapse" style="list-style-type: none; padding: 0%;">
    <li><a href="#">Simple Present Tense</a></li>
    <li><a href="#">Simple Perfect Tense</a></li>
    <li><a href="#">Simple Perfect Tense</a></li>
  </ul>
</div>

<button class="collapsible">Gelecek Zamanlar (The Future Tenses)</button>
<div class="content">
  <ul class="ulInCollapse" style="list-style-type: none; padding: 0%;">
    <li><a href="#">Simple Present Tense</a></li>
    <li><a href="#">Simple Perfect Tense</a></li>
    <li><a href="#">Simple Perfect Tense</a></li>
  </ul>
</div>

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

"Ensuring that every" within handlebars js

I have been exploring handlebars.js (hbs) and although I haven't mastered it yet, I am curious to know if there is an equivalent to the following code: {{#if all source}} If not, how can I create a similar functionality using handlebars.js? ...

An error was encountered: ReferenceError - Unable to locate google within the google.maps.Marker() function

<script src="https://maps.googleapis.com/maps/api/js?key=[KEY]&callback=initMap" async defer></script> <script> var user_lat,user_lng; var map; function initMap() { map = ...

What are the steps to correctly shut down an ExpressJS server?

I am facing a challenge with my ExpressJs (version 4.X) server - I need to ensure it is stopped correctly. Given that some requests on the server may take a long time to complete (1-2 seconds), I want to reject new connections and wait for all ongoing req ...

What is the proper way to create a child JSON object in Angular using TypeScript?

I have a model.ts file. export class MainClass { someVar: string; var2: string; subClass: SubClass; contact: ContactList; } export class SubClass { subItem: { item1: string; item2: string; item3: string; } constructor() ...

Maintaining consistency across all rows in a table with ng-repeat

I am currently working on a table that pulls data from a JSON file and uses ng-repeat to populate the columns. However, I need the first column (Line #) to remain static with values like 1, 2, 3, 4 to indicate the phone line the customer is on, while the r ...

Disabling pointer-events on material-ui textField input is ineffective

I have a material-ui textField input and I want to prevent the user from entering text by setting the css to pointer-events: none. However, this method does not work as expected. While I am aware that I can use the disabled={true} flag to disable the inpu ...

When the PHP function is invoked from JavaScript, no results are displayed

I need assistance with calling a PHP function from JavaScript. The goal is to call the PHP function and have it echo two arguments that are passed. However, the code I have written does not seem to be working as expected, as it does not print anything. Ca ...

HTML table featuring a stationary header row

I have designed an HTML page that consists of three sections: a header, a footer, and a table section sandwiched between the header and footer. The header and footer are fixed at the top and bottom respectively, with a specified height set using CSS (top:0 ...

Enable the central bootstrap button to expand and occupy the entire width

Here is a code snippet that I have: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>test</tit ...

Rule can be associated with only a single resource source, including the provided resource, test, include, or exclude

Hi there! I've encountered a persistent error with my Vue.js app that I can't seem to resolve. Even after reinstalling everything and clearing the cache, the issue remains. Any assistance would be greatly appreciated. Error: Rule can only have o ...

jQuery retrieve the element located below the current one within a table

I have a crossword puzzle and am attempting to automatically move the cursor to the next letter box after typing in a letter. I've figured out how to do this horizontally, but I'm unsure about moving vertically. My priority is to move horizontall ...

Eliminate unnecessary space from a Bootstrap 4 Card

Using the Card class from Bootstrap 4, I'm struggling with an extra space on the right side: https://i.sstatic.net/5qb8y.png (Please ignore the 'porno' thing, haha). You can clearly see the extra space on the right. I've been attemp ...

Tips for correctly sending the response code from a Node.js API

I have a straightforward node-based API that is responsible for parsing JSON data, saving it into a Postgres database, and sending the correct response code (e.g., HTTP 201). Here is an excerpt of my code: router.route('/customer') .post(fu ...

No change in the element's text content when clicking

I'm working on creating a timer that counts down from either 15 or 30 seconds. However, I'm having trouble changing the text value when the 15 button is clicked. Can someone help me figure out what's wrong? Thank you in advance HTML <h ...

Advancing past the stage of developing basic functions in the document.ready() event handler

When I develop a website, I have a personal preference of creating a main JavaScript file with window.load and window.ready functions at the top. I find it easier to refactor any logic into separate functions within these functions for better readability. ...

Issue with SmartNavigation in ASP.NET application using .NET 1.1

I am encountering an issue with a .Net 1.1 webapp where I have an aspx page with the attribute SmartNavigation=true set. Within this page, there is an anchor tag structured like this: <a href='#' onclick="$.copy('ANNUAL PAID OZ');" ...

MongoDB Query Fails to Fetch Documents with Matching Strings

I'm facing a peculiar issue where two seemingly identical strings are yielding different results in MongoDB. Below, I've pasted the two (seemingly distinct) strings with quotation marks on both sides (copied from Robo3T) to demonstrate any poten ...

Looking for a skilled JavaScript expert to help create a script that will automatically redirect the page if the anchor is changed. Any t

Seeking a Javascript expert, In my custom templates, I have used a link as shown below: <a href='http://www.allbloggertricks.com'>Blogging Tips</a> I would like the page to redirect to example.com if the anchor text is changed from ...

implement a night mode with a single click

I attempted to implement a dark mode using jQuery, but it is not working as expected. I am seeking assistance. I would like to enable the dark mode when clicking on the #btntheme ID, but for some reason, it is not functioning correctly. My goal is to be ...

The jQuery method .on gathers and retains click events

I created a component that manages a view containing articles with games. In order to prevent memory overload and optimize performance, I implemented a solution where when a user clicks on an article (each having the class "flashgame"), they can choose to ...