Can you guide me on how to replicate this for an additional 16 times? Apologies for the confusion

I need help with a code that can apply to multiple names at once, rather than one by one each time.

Here's the example HTML code:

<div id="one" class="text-container"> 
    <span> Campfire Cooking in Another World with my Absurd Skill</span> 
    <div class="fader fader-left"></div>
    <div class="fader fader-right"></div>
  </div>

And here is the corresponding JavaScript code snippet:

let container1 = document.querySelector("#one");
    let text1 = document.querySelector("#onespan");

    if (container1.clientWidth < text1.clientWidth) { 
      text1.classList.add("animate"); 
    }
  

I attempted implementing this code but it only applies to one name and not all of them.

Answer №1

Can this solution be of assistance?

let sections = document.querySelectorAll(".section");
let content = document.querySelectorAll("p");

for (let j=0; j<sections.length; j++) {
  if (sections[j].clientHeight < content[j].clientHeight) {
    content[j].classList.add("highlight");
  }
}

Answer №2

Solution

Instead of using querySelector to select a single element by its ID, we can utilize querySelectorAll to target multiple elements based on a class name. IDs should be unique, so it's better to use classes when selecting multiple elements.

    // Select all elements with the text-container class
    const containers = document.querySelectorAll(".text-container"); 
    
    
    for (let i=0; i<containers.length; i++) {
      // For each container, find the span element for animation
      const text = containers[i].querySelector("span");

      if (containers[i].clientWidth < text.clientWidth) {
        text.classList.add("animate");
      }
    }

Instead of a traditional for loop, you could also use a forEach method which some find easier to read and maintain. Use whichever method you feel most comfortable with!

    // Select all elements with the text-container class
    const containers = document.querySelectorAll(".text-container"); 
    
    containers.forEach((container) => {
        // For each container, find the span element for animation
        const text = container.querySelector("span");
    
        if(container.clientWidth < text.clientWidth) {
          text.classList.add("animate");
        }
      })      
    }

Recommendation

I suggest adding a specific class to those 16 elements to avoid accidental reuse. Using a generic name like .text-container is preferable over something more specific like .js-animated-card.

Prefixing your JS-related classes with js- can help differentiate them from purely styling classes. This makes it easier to manage and modify your styles without affecting your JavaScript functionality.

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

Position an anchor image at the top left corner, no matter the DTD or browser

Is there a way to keep an image with an href fixed in the top left corner of a webpage without affecting any other content and ensuring it functions consistently across different browsers and DTDs? I am facing the challenge of needing to provide a code bl ...

Breaking the lines in LESS

How can we instruct LESS to preserve line breaks in compiled CSS to enhance the cleanliness and readability of the code? Is there a way to configure LESS to maintain single-line CSS rules without adding line breaks between each selector, as shown in the e ...

Deactivate the button upon submission and reactivate it once the submission is complete

Recently, I've implemented a script that successfully sends data to the server using ajax. However, I now have a new requirement - I need to disable the button during submission and then re-enable it once the process is complete. $(document).ready(fu ...

Processing incoming requests with a loading interface in CodeIgniter

Is there a way to notify the user who sent the request whether or not the requested user will approve it? Optional: If there is no notification sent to the user who made the request, the requested user will have to wait for verification. For Example: Ima ...

Reactive forms in Angular now support changing focus when the Enter key is pressed

I have successfully created a table and a button that generates dynamic rows with inputs inside the table. One issue I'm facing is that when I press enter in the first input, a new row is created (which works), but I can't seem to focus on the ne ...

How can I dynamically update the status displayed in a DIV tag using PHP code?

I'm working on a web page where I am downloading data one by one in a continuous loop. Once each download is complete, I need to update the status displayed in a DIV tag on the webpage. The server connection and data download are handled by PHP code, ...

Ensure that the spacing between rows matches the spacing between columns

I am working on creating a 3x3 grid using Bootstrap. My goal is to have consistent spacing between the rows and columns. How can I achieve this effectively? ...

Shuffle the setInterval function: How to consistently rewrite with random intervals?

Seeking guidance on how to implement the following task: generate a random number after a random amount of time and then reuse it. function doSomething(){ // ... do something..... } var rand = 300; // initial random time i = setInterval(function(){ ...

Align the radio button, dropdown menu, and checkbox in a single row

I'm attempting to align a radio button, dropdown, and checkbox on the same line where the second radio button is displayed. I'm utilizing Bootstrap 4, but I'm open to plain HTML that doesn't necessarily follow Bootstrap styling. I trie ...

The function to focus on this.$refs[("p" + index)] element is not available

I need help transforming a div into an input box when clicked, allowing me to edit the post inside a loop. Here is the button found on the post: <a @click="setFocusEdit(index)" v-if="isAuthor(post)" href="#" >Edit Me</a> And here is the spec ...

Steps for executing a function once an AJAX call is completed inside an iframe

I am facing a challenge with extracting a variable value called useableData from an iframe back to the parent page. The page and iframe are both on the same domain. Inside the iframe, there is an AJAX call that populates some input fields with data, and I ...

Having trouble displaying the output on my console using Node.js

Hey there, I'm new to this community and also new to the world of nodejs technology. I have encountered a problem that may seem minor to you but is quite big for me. Here's what's going on: In my code snippet, I want a user to input 3 value ...

The @html.TextBoxFor model value does not appear pre-filled or set for the date type

I am using the @html.TextBoxFor method with a specified type of date. However, when rendering the view, the model value (retrieved from the database) is not being set. Here is an example of my code: <tr> <td>@Html.Label("ReferenceId")< ...

Select a specific element to apply a CSS selector for a button

One of the challenges I am facing involves a webpage with multiple submit buttons. My goal is to iterate through each button and click on them one by one. While I am aware that this can be achieved using xpath like this (//button[@class='submit' ...

The pagination in Laravel Vue is causing a validation error due to an invalid prop type check failing

Recently, I delved into working with Nuxt.js and decided to install the Laravel-Vue-Pagination plugin. However, I encountered an error message in my console system that reads: [Vue warn]: Invalid prop: type check failed for prop "data". Expected Object, ...

How can I access an object from a JavaScript file within a Laravel blade template?

I am trying to implement the package Sortablejs in my blade file. After installing it with npm, I created a sortable.js file within my assets folder containing the following code: import Sortable from "sortablejs"; This file is compiled into th ...

Access the $event object from an Angular template selector

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script> <input type="file" #myFile multiple /> <button (click)="onDelete(myFile.event)">DeleteFiles</button> My code snippet is experienci ...

Experiencing issues with passwords in nodemailer and node

Currently, I am utilizing nodemailer in conjunction with Gmail and facing a dilemma regarding the inclusion of my password. The predicament stems from the fact that my password contains both single and double quotes, for example: my"annoying'password. ...

How can you incorporate a Node.js require statement within an object literal and utilize it effectively?

Is there a possibility of any issues when using require as shown below? module.exports = { _ : require('lodash'), debug : require('debug'), moment : require('moment'), ...

Achieving (keyup.enter) event on an option within a datalist in Angular 6

How can I trigger the (keyup.enter) event on an option within a datalist in Angular 6? This is my HTML Code: <input list="filteredArray" (keyup)="filterEmployee(empForm.controls['empname'].value)" type="text" formControlName="empname" /> ...