Unable to target a specific child element with the :nth-child selector in JQuery/CSS

I am working on dynamically updating the id values of elements using JQuery/CSS selectors in a loop.

My goal is to have the click event on a button trigger a for loop that updates the id attribute of each

<div id='input_1' class="input row">
within the button_pro class.

The problem I am encountering is that I am unable to select and update my child IDs as the loop runs.

DEMO

HTML

<div class="button_pro">
    <div id='input_1' class="input row">
        <div class="input-field col s1">
            <input class="sno" type="text" name="Sr_1" value="1">
            <label for="Sr">Sr</label>
        </div>
        <div class="input-field col s2">
            <input id="item_code" type="text" name="item_code_1" value="">
            <label for="item_code">Item Code</label>
        </div>
    </div>
</div>
<div class="button_pro">
    <div id='input_1' class="input row">
        <div class="input-field col s1">
            <input class="sno" type="text" name="Sr_1" value="1">
            <label for="Sr">Sr</label>
        </div>
        <div class="input-field col s2">
            <input id="item_code" type="text" name="item_code_1" value=" ">
            <label for="item_code">Item Code</label>
        </div>
    </div>
</div>       
<br>

<button>Click</button>

JQuery/JavaScrit

$(function () {
    $('button').click(function () {
        var numof = $(".input").length;
        alert(numof);
        var i;
        for (i = 1; i <= numof; i++) 
        {
            $(".input:nth-child(" + i + ")").attr('id', 'input_' + i);
        }
    });
});

Thank You!

Answer №1

Opt for using eq().

:nth-child targets the nth child, while in your case where the elements are not direct children, it's better to use eq.

$(".input").eq(i).attr('id', 'input_' + i);

Remember that eq starts counting from zero, so make sure you adjust the for loop accordingly.

See Demo Here

$(function() {
  $('button').click(function() {
    var numof = $(".input").length;
    alert(numof);
    var i;
    for (i = 1; i <= numof; i++) {
      $(".input:nth-child(" + i + ")").attr('id', 'input_' + i);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div class="button_pro">
  <div id='input_1' class="input row">
    <div class="input-field col s1">
      <input class="sno" type="text" name="Sr_1" value="1">
      <label for="Sr">Sr</label>
    </div>
    <div class="input-field col s2">
      <input id="item_code" type="text" name="item_code_1" value="">
      <label for="item_code">Item Code</label>
    </div>
  </div>
</div>
<div class="button_pro">
  <div id='input_1' class="input row">
    <div class="input-field col s1">
      <input class="sno" type="text" name="Sr_1" value="1">
      <label for="Sr">Sr</label>
    </div>
    <div class="input-field col s2">
      <input id="item_code" type="text" name="item_code_1" value=" ">
      <label for="item_code">Item Code</label>
    </div>
  </div>
</div>
<br>

<button>Click</button>

Answer №2

    $(document).ready(function() {
        $(function() {
            $('button').on('click', function() {                    
                var elements = $(".input");
                var numberOfElements = $(".input").length;
                alert(numberOfElements);
                
                // Uncomment this block of code to assign unique ids to each input element
               /*
                var i;
                for (i = 1; i <= numberOfElements; i++) {
                   $(".input:nth-child(" + i + ")").attr('id', 'input_' + i);
                }
                */

                // Alternative way to assign unique ids using jQuery each method
                $(elements).each(function(i, item) {                        
                    $('#' + item.id).attr('id', 'input_' + 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

Organize the attributes of components on the following line in Visual Studio Code

Is there a method to configure the VS code formatter for Angular 2+ templates to ensure that attributes are wrapped in a new line? I prefer this formatting: <app [input1]="input1$ | async" [input2]="input2$ | async" (inputChanged)="set ...

Querying JSON Data in an Ajax Request: A Simple Guide

I have a data file in json format that looks like this: {"markers":[ { "latitude":11.58655, "longitude":122.755402, "type":"A"}, { "latitude":11.00698, "longitude":124.612801, "type":"B"}, { "latitude":10.30723, "longitude":123.898399, "type": ...

What significance does the symbol "'" hold in the ng-style attribute?

Can someone explain the purpose of the " \' " in this code snippet? <div ng-style="{ \'cursor\': row.cursor }" Is there a reason why it can't be written simply as <div ng-style="{ cursor: row.cursor }" Here is ...

How do you properly bind multiple events in jQuery and then unbind just a few of them?

Is it possible to bind multiple events, then unbind a couple of them? This is what I'm trying to achieve: When hovering over the element, the background color changes and changes back when hovering out. But when clicking the element, I want to disabl ...

Material User Interface, MUI, Modal, Back to Top Scroll按钮

After spending some time experimenting with scrollTop and the Dialog component (a fullscreen fixed modal) from Material-ui, I found that I couldn't quite get scrollTop to function properly. Whenever I clicked the "go down" button, it would either retu ...

Retrieve a collection of rows from a table by referencing a specific cell value

Is there a way to retrieve a list of rows from a table where one cell has a value of 0.00 without using a loop in jQuery? Preferably, with code that does not involve looping (avoiding the use of the each statement). <table id="products"> <tr> ...

Executing javascript function on hyperlink click

When using Response.Write to print a hyperlink like "Update", I am in need of a JavaScript function that will be triggered when the hyperlink is clicked. Can someone offer a solution for this issue? ...

At times, Vue.js may encounter difficulties when attempting to load a component

Recently, a strange issue has been occurring in my production code. Although nothing has been changed, I am now receiving reports that occasionally a template fails to load causing the page to crash. I am currently using vue 2.16. The error messages being ...

Accessing composable variables in Vue 3 without having to redefine refs from within a function

Currently, I am implementing a parent companyList component along with a reusable Table component and an useFetch composable in vue 3.2. Prior to integrating the Table component, my code looked like this: companyList <script setup> import { com ...

Navigating with Next.js Router: Dynamic URLs and the power of the back button

Utilizing the Router from the package next/router allows for a dynamic URL and loading of different content on the page: Router.push('/contract', `/contract/${id}`); An issue arises where the back button does not function as expected after runni ...

Height of container with full overflow for Bootstrap list-group

Currently, the list-groups in the screenshot are scrollable which is great, but I want them to occupy 100% of the remaining page height. I attempted using 100vh, but that didn't work due to other components on the page interfering. When I tried 100% h ...

A website utilizing single-page architecture and HTML navigation through servlet technology, all without the need to open additional pages

I am interested in downloading files using a servlet when a link is clicked. My website is built using single page architecture in HTML. How can I trigger a servlet without changing the page when a link is clicked? I have been attempting to achieve this ...

Ways to invoke a method in the parent component using a component/reactnode passed as props in a React application

I need to customize the Button component inside my Toast component. When I click on this custom button, I want it to call a method within the Toast component. Here is an example of how you can use the Toast component: const actionButton = ( <Mybutton ...

There is no element available to input text using send_keys in Selenium

Currently learning about selenium, please pardon any errors. Thank you :) I am trying to scrape a website that allows users to create blogs on 'tistory' using selenium. In order to publish an article, I need to choose between default mode, mark ...

CSS file not loading in an ExpressJS application

I'm facing an issue with my ExpressJS web app where only the HTML files are loading but the CSS rules are not being applied. I have linked the HTML file with the CSS file and also included express.static(path.join(__dirname, 'css')) in my ap ...

Unlocking, accessing and manipulating images stored locally using JavaScript, p5.js, and HTML

Being faced with the challenge of displaying an image file from a local folder using JavaScript (p5.js), I am continuously encountering the following error message: Access to image at "XXXXX" from origin "null" has been block by CORS policy: The response i ...

Issue with enabling drag behavior for JQuery resizable DIVs function in Wordpress

I'm attempting to create a layout with two divs positioned side by side, featuring a draggable center slider that can expand or contract the widths of these adjacent divs. To accomplish this, I've integrated the jQuery Resizable plugin. Although ...

The collapse menu on the navbar is noticeably narrower than the main navbar itself. What steps can I take to adjust this discrepancy? Additionally, the navbar is not visible on smaller screens

I am working on creating a sticky navbar that will collapse in smaller windows, such as smartphones. The first issue I am facing is the uneven width of the navbar compared to the actual design (see picture attached). Secondly, the navbar does not fade in w ...

Interfacing Node JS with Java Web Services via SOAP

I've been attempting to connect Java web services from a Node.js module, but I'm encountering an error in the wsdl library. Below is my wsdl file: <!-- Published by JAX-WS RI (http://jax-ws.java.net). RI's version is JAX-WS RI 2.2.9-b130 ...

Moving files by dragging and dropping rather than deleting them

I have successfully implemented a feature using JavaScript to drag and drop multiple files, followed by displaying those images. The code below is fully functional without any errors. Need help with: I am now looking to add the ability to remove these ima ...