Alex Parker
Alex Parker

Reputation: 1583

How to select the nth child of each subsequent sibling

I have some HTML that looks like this:

<tbody>
    <tr id="upload_row_0">
    <tr id="upload_row_1">
    <tr id="upload_row_2">
        <td>
            <select name="task_exec_platform">
        </td>
        <td>
            <input type="file" name="task_exec_config_2">
        </td>
        <td>
            <input type="file" name="task_exec_2">
        </td>
        <td>
            <a onclick="deleteTaskExecRow("#upload_row_2")">
        </td>
    </tr>
</tbody>

Each row expands and includes similar <td> elements, but I am just showing a snippet for brevity's sake. The id "upload_row_0" is stored in a variable, obj.

I want to select the 2nd child of each subsequent sibling row. In other words, I want to change the name "task_exec_config_2" for rows 1 and 2. I am able to capture all the subsequent rows using nextAll(), but I am unsure how to select the 2nd child for each of those elements. My current attempt is

$(obj).nextAll().$(":nth-child(2)").children().attr("name", "new_name");

but I know that this isn't right.

Thanks!

Upvotes: 0

Views: 93

Answers (4)

Alex Parker
Alex Parker

Reputation: 1583

Here is the solution that I came up with myself. eq() will get a specific child, and then I also needed to select the <input> tag in order to change the name appropriately. I just made a mistake in the question by forgetting that name was on <input> and not <td>.

$(obj).nextAll().children().eq(1).children("input").attr("name", "new_name");

Upvotes: 0

PhilVarg
PhilVarg

Reputation: 4820

i think you just want to move nth-child into next all

$(obj).nextAll(':nth-child(2)').attr("name", "new_name");

Update
Going off you're original one, i see what youre trying to do.

$(obj).nextAll().$(":nth-child(2)").attr("name", "new_name");

you need to replace the $.(...) after nextAll with find, and select the child input

$(obj).nextAll().find(":nth-child(2) input").attr("name", "new_name");

made a fiddle to visually see what you're selecting:
https://jsfiddle.net/9oqj3z78/2/

Upvotes: 2

Ben Koehler
Ben Koehler

Reputation: 8681

Change your second '$' to 'find'

$(obj).nextAll().$(":nth-child(2)").attr("name", "new_name");

to

$(obj).nextAll().find(":nth-child(2)").children().attr("name", "new_name");

Upvotes: 3

connexo
connexo

Reputation: 56754

$("#"+obj)
     .parent('tbody')
         .find('tr')
             .find('td:nth-child(2)')
                 .find('input')
                     .attr('name','new_name');

Upvotes: 0

Related Questions