Number each element in sequence

Looking to give sequential numbering to elements by iterating through them.

For instance, if there are 6 input elements, the goal is to update their names correspondingly like "name=input1", "name=input2", and so on. This involves using a for loop to reassign names each time an element is added or removed.

Below is the function that's attempted (and struggling) to be executed:

function count(){
    console.log(numChildren)
    var childCount = document.getElementById("items").childElementCount;
    console.log(childCount + " = number of children")
    numChildren = [];
    for (var i = 0; i < childCount; i++) {
        numChildren.push(i+1)
        document.querySelector("input[name*='item_name_']").name = "item_name_" + numChildren[i];
    }
};

Answer №1

If you're looking for a solution, you could try something along the lines of:

const elements = document.getElementById("items").children;
        
 for (var j = 0; j < elements.length; j++) {

       elements[j].setAttribute('title', 'element_title_'+(j+1));

  }
<html>

<body>
    <div id="items">
        <input type="text" title="element_1" />
        <input type="text" title="element_2" />
        <input type="text" title="element_3" />
        <input type="text" title="element_4" />
    </div>
</body>
</html>

Answer №2

If you want to modify the names of certain input elements in a collection, you can easily achieve this using a forEach loop and referencing the index as you iterate through each element.

  let inputs = document.querySelectorAll("#items input[name*='item_name_']");
inputs.forEach((el, index) => { el.setAttribute('name', 'item_name_'+index); })
<div id='items'>
  <input type='text' name="item_name_99" />
  <input type='text' name="item_name_19" />
  <input type='text' name="item_name_8" />
  <input type='text' name="item_name_3" />
  <input type='text' name="item_name_49" />
  <input type='text' name="item_name_9" />
</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

One effective way to utilize await/async within the Vue mounted lifecycle hook is by

I am facing an issue where the mapGetters value is showing null in my computed property because the preferences method is not executed completely. I need to wait until the store has set the getter and setter. I have tried using async/await but it's no ...

Is there a reason why the JSX select element does not automatically select the option (implementing 'selected')? I'm unsure if I am overlooking something

In my HTML, I have a snippet of code that defines a custom <SelectField> component using a <select> tag like this: export default function SelectField(props) { /* PARAMETERS: - fieldname (String) - fieldID (String) - options (A ...

Struggling to grasp the concept of async/await and promises

I'm fairly new to working with node.js and JavaScript in general. I've been trying to understand promises and async/await concepts, specifically in the context of requesting images from a remote URL asynchronously and converting them to base64 fo ...

Ways to dynamically apply styles to the component tag depending on the visibility of its content

Consider a scenario where you have a component with logic to toggle the visibility of its contents: @Component({ selector: 'hello', template: `<div *ngIf="visible"> <h1>Hello {{name}}!</h1></div>`, styles: [`h1 { fo ...

Utilizing absolute path in Typescript: A comprehensive guide

I am currently working on a project written in Typescript running on NodeJS. Within the project, I have been using relative paths to import modules, but as the project grows, this approach is becoming messy. Therefore, I am looking to convert these relativ ...

A step-by-step guide on how to use the Google Closure Compiler: a

Is there anyone who could assist me in adding a snippet to the basic process of Google Closure Compiler? I have been trying unsuccessfully to do this via JavaScript code. I am using an example snippet from the official npm page, but when I run it, someth ...

Unable to dynamically change the value of the submit button using angular.js

I'm facing an issue with setting the submit button value dynamically using Angular.js. The code I've written below explains my problem. <body ng-controller="MainCtrl"> <input type="submit" value="{{ !model ? 'reset' : mod ...

Sending data as a string in an AJAX request

I have been struggling with this coffeescript function that controls dynamic select boxes. I am trying to pass the content of "modelsSelect" to another script, but for some reason, it's not working as intended. customScript.coffee dynamicSelection = ...

I am uncertain about how to interpret this method signature

Can you help me determine the correct method signature for handleError? The linter tslint is indicating an error message that says expected call-signature: 'handleError' to have a typedef (typedef). Here is the code snippet in question: import ...

At the ready stance for a particular grade of students attending a class

I have created a page with a navigation menu that can be scrolled using the wheel mouse. My goal is to ensure that the li item with the 'selected' class is always positioned in the first position on the left. Is there a way to achieve this using ...

Access information through the restful api using the angularjs service $resource

I am attempting to utilize the $resource service with the surveygizmo API. Here is my code: HTML : <div ng-app="Survey"> <body> <div ng-controller="SurveyCtrl"> {{survey.data.title}} </div> </body> </div> My scr ...

Incorporating CSS Styles in EJS

Struggling with connecting my CSS files while using EJS. I've checked out another solution but still can't seem to get it right. Here is the code I used as a reference for my CSS file. EJS <html> <head> <meta charset="utf-8 ...

Creating a Draft.js selection with a specified start and end point

Looking for a way to replace the last insertion in Draft.js For instance, Original string -> aaazzz After inserting 'bbb' in the middle -> aaabbbzzz Replace last insert with 'ccc' -> aaaccczzz Replace last insert with &apos ...

How can I automatically update the content of a specific Div element when the page is loading using the Ajax load() function

This is the HTML code I have: <body onload="fun1()"> <ul id="nav" class="nav" style="font-size:12px;"> <li><a href="#" id="m_blink" onclick="fun1()">Tab1</a></li> <li><a href="#" id="d_blink" onclick="f ...

What is the best way to convert an Angular object into a string using a for-loop and display it using $sce in AngularJS?

Currently, I am rendering a block of HTML and directives using $sce.trustAsHtml. To achieve this, I utilized a directive called compile-template which enables the use of ng-directives like ng-click and ng-disabled. While it is possible for me to pass sta ...

Having difficulty inputting password for telnet login using Node.js

When I use telnet from the Windows command line, everything works smoothly: > telnet telehack.com (... wait until a '.' appears) . login username? example password? (examplepass) * * * * * * * Logged... (...) @ (This is the prompt when you ...

Display or conceal specific fields depending on the selection from a dropdown menu

I'm currently experimenting with using JavaScript and/or jQuery to dynamically hide specific HTML elements based on the selection in a drop down menu. Here is what my page setup looks like: [Drop down menu] [text field 1] [text field 2] [text field ...

How to toggle a boolean variable in AngularJS when transitioning between states

Just getting started with AngularJS and trying to figure out how to tackle this issue. I have set up the following route: name: "Tracker", url: "/tracker/:period", and I have 3 distinct states for which I've created 3 separate functions to facilit ...

What happens if you try to add a member to a Mailchimp list who is already on the list

After following Angela Yu's course for the past few weeks, I attempted to implement the Mailchimp API as she demonstrates. However, I encountered difficulties due to recent changes in Mailchimp. Despite this setback, I was able to find the API referen ...

Two separate occurrences hold identical values

I'm encountering an issue where instantiating a class two times results in the second instance retaining parameters from the first instance. Here's a simple example: var Test = function() {}; Test.prototype = { bonjour: null, hello: { h ...