How can one selectively apply a class to the initial DIV within a collection of dynamically generated DIV elements without relying on jQuery?

I am currently working on implementing a slideshow within a modal using AngularJS and Bootstrap. My challenge lies in dynamically creating DIVs, but specifically adding the active class to only the first DIV.

Is there a way to achieve this without relying on jQuery?

Additionally, I am curious if there are alternative methods to accomplish the same functionality. Any suggestions or guidance would be greatly appreciated.

Below is the code snippet:

<!DOCTYPE html>
<html ng-app="modalApp">
  <head>
    <title>Custom Modal Implementation</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
    <script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
    <script src="app.js"></script>
  </head>
  <body>
    <div ng-controller="modalAppController">

      <button class="btn btn-primary" data-toggle="modal" data-target="#whatsNewModal">Open Modal</button>
      <!-- Whats New feature modal -->
<div id="whatsNewModal" class="modal fade" role="dialog">
    <div class="modal-dialog modal-lg">
      <div class="modal-content">

        <!-- Modal Header -->

        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">x</button>
          <h3 class="modal-title" style="color: #000"><strong><i class="fa fa-bullhorn" style="margin-right: 10px"></i><span>What's New</span></strong></h3>
        </div>

        <!-- Modal Body / Modal Content -->

        <div class="modal-body">
          <div id="whatsNewCarousel" class="carousel slide" data-ride="carousel" data-interval="3000">

            <!-- Carousel Images -->

            <div class="carousel-inner" role="listbox" id="carousel-in">

              <div id="carouselContent">

              </div>


            <!-- Carousel Controls -->
                <a class="left carousel-control" href="#whatsNewCarousel" role="button" data-slide="prev" style="background: transparent">
                  <span class="glyphicon glyphicon-chevron-left" aria-hidden="true" style="color: #dcdde1; top: 40%; left: 10px; font-size: 40px"></span>
                  <span class="sr-only">Previous</span>
                </a>
                <a class="right carousel-control" href="#whatsNewCarousel" role="button" data-slide="next" style="background: transparent">
                    <span class="glyphicon glyphicon-chevron-right" aria-hidden="true" style="color: #dcdde1; top: 40%; right: 22px; font-size: 40px"></span>
                    <span class="sr-only">Previous</span>
                </a>


          </div>
        </div>

      </div>
    </div>
</div>
    </div>
  </body>
</html>

app.js

(function(){
  'use strict';

  angular.module('modalApp', [])
  .controller('modalAppController', modalAppController)
  modalAppController.$inject = ['$scope'];
  function modalAppController($scope){
    $scope.carouselData = function(src, head, desc){

// Creation of item div

      $scope.carouselCon = document.getElementById("carouselContent");
      $scope.newDiv = document.createElement("DIV");
      $scope.newDiv.setAttribute("class", "item active");
      $scope.carouselCon.appendChild($scope.newDiv);


// Creation of Image Element

      $scope.image = document.createElement("img");
      $scope.image.setAttribute("src", src);
      $scope.image.setAttribute("class", "img-fluid d-block");
      $scope.newDiv.appendChild($scope.image);

// Creation of Image Content

      $scope.h3 = document.createElement("H3");
      $scope.h4 = document.createElement("H4");

      $scope.h3Content = document.createTextNode(head);
      $scope.h4Content = document.createTextNode(desc);
      $scope.newDiv.appendChild($scope.h3.appendChild($scope.h3Content));
      $scope.newDiv.appendChild($scope.h4.appendChild($scope.h4Content));

    };

    $scope.carouselData("Screen.png", "Feature 1", "Here goes the description");
    $scope.carouselData("Screen2.png", "Feature 2", "Here goes the description"); // More functions like this can be added.
  }
})();

Answer №1

Absolutely! You have the ability to target a single div by utilizing the CSS :first-child Selector.

let selectedElement = angular.element(document.querySelector('.classname:first-child'));
selectedElement.addClass("new_class_name");

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

Can these two arrays be merged together in JavaScript?

Here is the structure of the first array: [ 0:{program: id_1}, 1: {program: id_2} ] Now, let's take a look at the second array: [ 0: [ 0: {lesson: name_1}, 1: {lesson: name_2} ], 1: [ 0: {lesson: name_3} ] ] I am attempti ...

Changing the color of a specific span using Angular

I am working with a dynamic mat-table where columns are added and populated on the fly. The table headers are styled using divs and spans. My goal is to change the color of a header to black when clicked, but also un-toggle any previously selected header. ...

Postpone the processing of a message in the Service Bus Queue until a specific time using NodeJS

Despite trying multiple tutorials, I have been unable to achieve the desired result so far. Currently, my setup involves a nodejs app that sends messages to the Service Bus Queue and another nodejs app that continuously polls it. The goal is to schedule a ...

Guide to importing firebase-functions and firebase-admin using ES6 syntax for transpilation with Babel in Node 10

I've been working on my cloud functions in ES6 and using Babel to transpile them for the Node v10 environment. But, I've come across an odd issue. It seems that when I import firebase-functions like this: import functions from 'firebase-fu ...

Promise chain failure in express

I've developed an express.js server for managing REST API requests and extracting data from a MongoDB database. However, I'm encountering an issue with the promise chain when I send a GET request to a specific endpoint ("localhost:8081/api/getUse ...

How should event listeners be unbound and child elements removed in single page applications?

I've recently delved into the world of memory leaks in JavaScript while working on a large single-page application. After using Chrome's Profiles (Snapshot) function, I noticed an abundance of detached DOM elements indicating a possible memory le ...

Determining if a path is within the same directory: a step-by-step guide

I need to check if the input path is located in the same folder or not Question: Is the input path in the same folder? For example, if my current path is f://learning/java and I am currently in a folder named java, then any path that directly belongs to ...

Develop a game timer using CreateJS

Looking for advice on the most effective method to create a timer clock using Createjs. I've attempted to reference HTML elements with DOMElement in the past, but encountered difficulties. Essentially, I need to display a timer within a container so p ...

Adding data to a multidimensional array in JavaScript

I am in need of creating a multidimensional JavaScript array dynamically, following this specific structure: array_answers[0][1]:"yes" array_answers[1][2]:"no" array_answers[2][2-subquestion]:"text input" array_answers[3][8]:"yes" array_answers[4] ...

Synchronizing jQuery parameters

I have developed a JavaScript shopping basket where the total sum updates automatically when a quantity is selected. However, I encountered an issue where the total value does not update when a product is removed unless the page is refreshed. Here's ...

Code for a regular expression that permits either letters or numbers with symbols

Here is the code snippet I am using for data validation in jQuery: return /^(?=.*[A-Za-z0-9/\$#.-_])[A-Za-z0-9/\$#.-_]$/i.test(value) The requirement is that the value should begin with letters or numbers, or a combination of both. Afterwards, ...

Changing route parameters or query parameters does not trigger a reload of component data in React

The "home" component has links that direct to the product component when clicked. Another component always visible displays links to recently visited products. However, on a product page, these links fail to work properly. Although the URL updates and tri ...

Every time I refresh the page, the user is automatically logged out

I am currently working on developing an admin dashboard using nextjs 13. I have encountered a specific issue where the user is redirected to the login page every time they reload the page. Upon inspecting in developer mode, I noticed that cookies are still ...

Refreshing Ajax in a different tab causes the selectize element to become unbound from the editing form in Rails 5

In my Rails 5.1 application, I have multiple views with the main view being the calls index view. In this view, I perform an ajax refresh of partials and use a callback to re-initialize the selectize JS element in the calls/index view as shown below: < ...

Struggling to deserialize JSON information into a Dictionary with key and value pairs of strings

Looking to convert this JSON data into a Dictionary using native Javascript. var jsonData = "{"Symptom":[true,true,true],"Action":[true,true],"AllArea":true}"; However, encountering an error when trying to deserialize it with the following code: Diction ...

Ways to continuously execute a JavaScript click event

Hello everyone! I've been a long time reader, but this is my first time posting. I'm completely new to this and need some help. How can I modify the code so that "ele.click();" will be triggered multiple times with a single press of the "Z" key? ...

Ways to attach an item using its lower point instead of its upper coordinate

I am currently working on a poker table project using React. As of now, I have player components that need to be strategically positioned around the table. One challenge I'm facing is that when the screen attribute changes, the position of the top tw ...

Updating information on separate controllers in AngularJS

Starting out on this new framework. I have a query regarding updating a controller from another controller. I know this question has been asked numerous times. But my issue is unique to me. I can solve it using rootScope, but I'm not a fan (Am I ...

Using jQuery and Perl to create a dynamic progress bar that is based on the current state of a "pipeline file" and utilizes AJAX

I'm looking to create a small pipeline that enables users to select a file and run multiple scripts using it as an input. Some of these scripts may take several minutes to complete (time depends on the file's size), so I want to display a progres ...

Utilizing Typescript Generics in Arrow Function to Combine Two Arguments

For instance, I am working with this code in a .tsx file extension const Add = <T,>(arg0: T, arg1: T): T => arg0 + arg1; const A = Add(1, 2); const B = Add('1', '2') However, I am encountering an issue, as there is an error m ...