Padaca
Padaca

Reputation: 337

How can I change the id of an element within a div I've assigned to a variable in JQuery?

If I've got some html with nested elements:

<body id="body">
    <div id="outer-div-0">
        <div id="inner-div-0">
        </div>
    </div>
</body>

And some JQuery that assigns the outer div to a variable:

var $div = $('div[id^="outer-div-"]:last');

Can I use the $div variable to change the id inner-div-0?

I'm doing this because I have some JQuery that clones outer-div-0 when a user clicks a button, as it's possible the user will need multiple instances of the div (it's an input form, so I have to buttons that allow the user to add and subtract as many copies of the form as are needed). I already have some code which increments the id of the outer div for every clone. So right now, when I click the button to add a new div, it ends up looking like

<body id="body">
    <div id="outer-div-0">
        <div id="inner-div-0">
        </div>
    </div>
    <div id="outer-div-1">
        <div id="inner-div-0">
        </div>
    </div>
</body>

Here's the JQuery that does that:

var $div = $('div[id^="outer-div-"]:last');
initNum = parseInt($div.prop("id").match(/\d+/g), 10) + 1;
var $newDiv = $div.clone().prop('id', 'outer-div-' + initNum);
$("#body").append($newDiv).html();

Of course, I also have to increment the id of the inner div, but I'm having trouble figuring it out.

I should add, I'm using ids for the inner div because they have labels with a for attribute. I've left these out for simplicity as they don't really add to the question. In addition, the actual code has more than one inner-div. Again, left out for the sake of simplicity.

Any thoughts on how to do this? I've been scratching my head over it for a few hours now. Thanks!

Upvotes: 0

Views: 108

Answers (1)

Barmar
Barmar

Reputation: 781004

You can use .find() on the cloned DIV

$newDiv.find("[id^=inner-div-]").attr('id', 'inner-div-' + initNum);

Upvotes: 1

Related Questions