mr. jman mr. jman - 1 month ago 6
CoffeeScript Question

JavaScript / CoffeeScript rename id of cloned nested div assigned to a variable

I would like to clone the

outer_div
in the html below using CoffeeScript in my Rails app and then change the
id
of
inner_div
to an
mSec
timestamp.

View



<div class="col-xs-12" id="outer_div">
<div class="col-xs-3" id="inner_div">
Hello World
</div>
</div>

<input type="button" value="Submit" id="submit_button" class="btn add-text-input">

<div class="col-xs-12" id="new"></div>


CoffeeScript



ready = ->
$("#submit_button").click ->
date = new Date
mSec = date.getTime()
name = $('#outer_div').clone()
name.attr 'id', mSec # <-- need to change this line of code
$("#new").append(name);
return
$(document).ready(ready)


The
name.attr 'id', mSec
code changes the
id
of the
outer_div
, but I would like to change the
id
of the
inner_div
. What changes do I have to make to my code to target the `inner_div'?

Answer

Use find on name to search for #inner_div within your clone:

name.find('#inner_div').attr(id: mSec)

That will give you the id attribute you're after but you'll still have duplicate id="outer_div" elements and that's not valid HTML. You should change the id attribute on name too; you probably don't need the id on the clone so you could use removeAttr to remove it:

  name.removeAttr('id').find('#inner_div').attr(id: mSec)

Demo: https://jsfiddle.net/ambiguous/rd25b2ey/