Customize list items using IDs once they have been generated

My vertical timeline is dynamically generated with <li> elements that have an ::after pseudo-class.

I want to style specific circular elements after the timeline creation (only changing the color of the circles). I am struggling to add a class to individual elements post-creation.

After reviewing @RCC's response: The code provided selects the elements but doesn't change their colors. Is there a way to style the ::after class of certain list elements using JavaScript? Any insights would be helpful!

myArr = ['elem1', 'elem3', 'elem8']

 for (var i = 0; i < myArr.length; i++) {

var elem=document.getElementById(myArr[i])
console.log(elem)
elem.className += ".timeline ul li.newstyle::after {background:#3887be}";

}
*,
*::before,
*::after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font: normal 16px/1.5 "Helvetica Neue", sans-serif;
  background: #ffffff;
  color: #404040;
  overflow-x: hidden;
  padding-bottom: 50px;
}  


/* INTRO SECTION
–––––––––––––––––––––––––––––––––––––––––––––––––– */

.intro {
  background: #FFFFFF;
  padding: 100px 0;
}

.container {
  width: 90%;
  max-width: 1200px;
  margin: 0 auto;
  text-align: center;
}

h1 {
  font-size: 2.5rem;
}


/* TIMELINE
–––––––––––––––––––––––––––––––––––––––––––––––––– */
.timeline ul li {
  list-style-type: none;
  position: relative;
  width: 6px;
  margin: 0 auto;
  padding-top: 50px;
  background: #404040;
}

.timeline ul li::after {
  content: '';
  position: absolute;
  left: 50%;
  bottom: 0;
  transform: translateX(-50%);
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: inherit;
}

.timeline ul li div {
  position: relative;
  bottom: 0;
  width: 400px;
  padding: 15px;
  background: #FFFFFF;
}

.timeline ul li div::before {
  content: '';
  position: absolute;
  bottom: 7px;
  width: 0;
  height: 0;
  border-style: solid;
}

.timeline ul li:nth-child(odd) div {
  left: 45px;
}

.timeline ul li:nth-child(odd) div::before {
  left: -15px;
  border-width: 8px 16px 8px 0;
  border-color: transparent transparent transparent transparent;
}

.timeline ul li:nth-child(even) div {
  left: -439px;
}

.timeline ul li:nth-child(even) div::before {
  right: -15px;
  border-width: 8px 0 8px 16px;
    border-color: transparent transparent transparent transparent;
}

/* LEFT JUSTIFY
–––––––––––––––––––––––––––––––––––––––––––––––––– */

.timeline ul li {
    margin-left: 20px;
  }
  
  .timeline ul li div {
    width: calc(100vw - 91px);
  }
  
  .timeline ul li:nth-child(even) div {
    left: 45px;
  }
  
  .timeline ul li:nth-child(even) div::before {
    left: -15px;
    border-width: 8px 16px 8px 0;

  }
<section class="intro">
  <div class="container">
    <h1>Vertical Timeline &darr;</h1>
  </div>
</section>

<section class="timeline">
  <ul>
    <li id='elem1'>
      <div>
        <time>1934</time> At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium
      </div>
    </li>
    <li id='elem2'>
      <div>
        <time>1937</time> Proin quam velit, efficitur vel neque vitae, rhoncus commodo mi. Suspendisse finibus mauris et bibendum molestie. Aenean ex augue, varius et pulvinar in, pretium non nisi.
      </div>
    </li>
    <li id='elem3'>
      <div>
        <time>1940</time> Proin iaculis, nibh eget efficitur varius, libero tellus porta dolor, at pulvinar tortor ex eget ligula. Integer eu dapibus arcu, sit amet sollicitudin eros.
      </div>
    </li>
    <li id='elem4'>
      <div>
        <time>1943</time> In mattis elit vitae odio posuere, nec maximus massa varius. Suspendisse varius volutpat mattis. Vestibulum id magna est.
      </div>
    </li>
    <li id='elem5'>
      <div>
        <time>1946</time> In mattis elit vitae odio posuere, nec maximus massa varius. Suspendisse varius volutpat mattis. Vestibulum id magna est.
      </div>
    </li>
    <li id='elem6'>
      <div>
        <time>1956</time> In mattis elit vitae odio posuere, nec maximus massa varius. Suspendisse varius volutpat mattis. Vestibulum id magna est.
      </div>
    </li>
    <li id='elem7'>
      <div>
        <time>1957</time> In mattis elit vitae odio posuere, nec maximus massa varius. Suspendisse varius volutpat mattis. Vestibulum id magna est.
      </div>
    </li>
    <li id='elem8'>
      <div>
        <time>1967</time> Aenean condimentum odio a bibendum rhoncus. Ut mauris felis, volutpat eget porta faucibus, euismod quis ante.
      </div>
    </li>
  </ul>
</section>

Answer №1

Give this a shot:

const myArray = ['element1', 'element3', 'element8'];

for (let i = 0; i < myArray.length; i++) { // "i" represents the index!
  const element = document.getElementById(myArray[i]); // Accessing each item using "myArr[i]"
  element.className += " new-style";
}

Remember to use var before declaring variables.

Don't forget to add the new class in your CSS:

.timeline ul li.new-style::after {background:#3887be}

Take a look at the following link for reference: https://jsfiddle.net/rcheruti/qeb1yzu0/6/

Answer №2

follow this path

include in your css

.timeline ul li.newStyle::after { /* TIMELINE + newStyle –––– */
  background  :#3887be;   
  }

update your JS :

const myList = ['elem1', 'elem3', 'elem8']

myList.forEach( item =>
  document.getElementById(item).classList.add('newStyle')
  )
*,
*::before,
*::after {
  margin     : 0;
  padding    : 0;
  box-sizing : border-box;
  }
body {
  font           : normal 16px/1.5 "Helvetica Neue", sans-serif;
  background     : #ffffff;
  color          : #404040;
  overflow-x     : hidden;
  padding-bottom : 50px;
  }
/* INTRO SECTION –––––––––––––––––––––––––––––––––––––––––––––––––– */
.intro {
  background : #FFFFFF;
  padding    : 100px 0;
  }
.container {
  width     : 90%;
  max-width : 1200px;
  margin    : 0 auto;
  text-align : center;
  }
h1 {
  font-size : 2.5rem;
  }
/* TIMELINE–––––––––––––––––––––––––––––––––––––––––––––––––– */
.timeline ul li {
  list-style-type : none;
  position        : relative;
  width           : 6px;
  margin          : 0 auto;
  padding-top     : 50px;
  background      : #404040;
  }
.timeline ul li::after {
  content       : '';
  position      : absolute;
  left          : 50%;
  bottom        : 0;
  transform     : translateX(-50%);
  width         : 30px;
  height        : 30px;
  border-radius : 50%;
  background    : inherit;
  }
.timeline ul li.newStyle::after { /* TIMELINE + newStyle –––– */
  background  :#3887be;   
  }
.timeline ul li div {
  position   : relative;
  bottom     : 0;
  width      : 400px;
  padding    : 15px;
  background : #FFFFFF;
  }
// More CSS code...
  <section class="intro">
    <div class="container">
      <h1>Vertical Timeline &darr;</h1>
    </div>
  </section>
  
  <section class="timeline">
    <ul>
      // HTML code for timeline items...
    </ul>
  </section>

Answer №3

It seems like you may have overlooked the importance of fetching the string value from the array.

Please consider using

elem=document.getElementById(myArr[i])

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

Place elements at the bottom of a webpage on any browser or device with just a single page

I am in the process of creating a website that features a top menu and a background image with text on the home page, covering the full screen. However, I also need to include 3 blocks at the bottom of the screen that should display consistently across all ...

Retrieve the element's value in relation to a different parent element

[JavaScript] How can I access the value of a textbox related to a button through jQuery? The event is triggered when the .button-action is clicked <td class="dmsInput"> <input type="text" maxlength="4" size="4" class="d"> </td> <td& ...

Enhancing jQuery functionality: Ensuring newly added elements are aware of existing functions

I need assistance with my HTML table. Each row (tr) contains a value, for example 200$, and a delete button. How can I ensure that each new row added automatically knows the recent functions without having to call them every time? $(function () { $(&ap ...

Utilizing BeautifulSoup 4 to extract JSON data from Script tags in HTML

Looking to extract the code from this webpage link Currently using python with json and bs4. See full page source here: https://pastebin.com/iU5c9GBF <div class="Actions"> <input class="action" type="subm ...

Upon refreshing the page, next.js 13's useSession() function fails to fetch session information

Currently, I am working on replicating an ecommerce site using nextjs 13. On the order page, I am utilizing useSession from next-auth/react to check if a user is signed in or not. Everything works fine when I navigate to the page through a link, but if I r ...

Is it achievable to animate the offset with React Native Animated?

I am attempting to develop a dynamic drag and drop functionality, inspired by this example: My goal is to modify it so that when the user initiates the touch, the object moves upwards to prevent it from being obscured by their finger. I envision this move ...

The Angular directive is failing to acknowledge the attribute

Check out the following HTML: <body ng-app="myCatApp"> <div ng-controller="catagoryController"> <add-remove-lister list="catagories"></add-remove-lister> </div> </body> And here is the J ...

jqgrid now features inline editing, which allows for the posting of only the data that

My jqGrid includes editable columns, and I am looking for a way to only post the data of columns where changes have been made. Here is an example of my colModel: colModel: [{ name: 'I_PK', index: 'u.I_PK ...

The error message "vue-router encountered an unexpected token import" popped

Trying to find a way to store my Vue templates in variables for routing purposes. I've set up an App.vue file with just a simple HTML title (for testing), and a main.js file with an 'import' statement that I haven't used in JavaScript ...

Retrieving URL parameters and excluding a particular parameter from the list

I am looking to extract a specific parameter from the URL. Here is my scenario: Initially, the page loads with a URL like this: Upon loading the page, a function is triggered to add an entry to the history using pushState, resulting in a new URL such as ...

Dynamic Dropdown Navigation with Bootstrap 4

I noticed that the default Bootstrap (4.0) dropdown animation is not present. How can I achieve a "slide" open effect similar to the collapsed navbar? It should be mentioned that the dropdown is located within the navbar. You can find the codeply example ...

What is the correct syntax for declaring a variable within a switch statement in TypeScript?

How can I properly use a switch statement in TypeScript to assign a new variable a value? For example: let name: string switch(index) { case 0: name = "cat" case 1: name = "dog" .... } I keep getting the err ...

Is there a way to schedule a function to run every 6 hours in node.js based on actual time instead of the device's time?

var currentTime = new Date().getHours(); if(currentTime == 6){ //function Do stuff } if(currentTime == 12){ //function Do stuff } if(currentTime == 18){ //function Do stuff } if(currentTime == 24){ //function ...

Utilizing Environment Variables during the build process in a VueJS project

During the build stage of a CI job for my VueJS app, I am attempting to utilize an environment variable provided by GitLab CI called CI_COMMIT_SHORT_SHA. build: image: node:latest stage: build variables: CI_COMMIT_SHORT_SHA: "$CI_COMMIT_SHORT_S ...

Is the boolean condition in my Angular template not updating properly when the state changes?

I am attempting to modify a template when a specific pie chart slice is clicked. Here is the template code: <h1>{{slice && slice.name}}</h1> <h1>{{slice && slice.value}}</h1> Check out this demo: https://st ...

Applying jQuery .animate() to elements without specifying position: absolute

My goal is to create a website where clicking on an image triggers a dropdown menu. The jQuery method I'm using is as follows: function main() { $('#arrow').click(function() { $('.hidden').animate({ top: &a ...

Utilizing an External Variable in a Callback Function in Node.js / Express.js

Currently, I am utilizing a library known as node-geocoder within express js with the code snippet provided below: var NodeGeocoder = require('node-geocoder'); var options = { provider: 'google', // Additional values may be nece ...

Using jQuery's .append() method within a for loop

As a newbie in JavaScript, I've been trying to find answers to my questions, but the solutions I've come across are quite complex for my level of understanding. One specific issue I'm tackling involves creating a grid of divs using user inpu ...

React - Implementing dynamic component rendering on a webpage

My component, Item.js, is static. Routes.js export default () => ( <Provider store={store}> <BrowserRouter> <Switch> <Route path="/posts" component={Posts} /> <Route path="/form" component={Postfo ...

The JavaScript rock, paper, scissors application is experiencing issues with displaying correctly

Currently, I am in the process of learning JavaScript and working on developing a rock, paper, scissors game using only JavaScript. The game will have two modes- a single round mode and a three-round mode. However, after completing the code for the singl ...