February 8, 2012
Insert parent element ID into dynamic element
Question by GSTAR
Markup:
<iframe id="portal">
<div id="callout-1" class="callout">
</div>
<div id="callout-2" class="callout">
</div>
</iframe>
$(document).ready(function(){
$('#page-portal').load(function(){
$('#portal').contents().find('.callout')
.append('<div class="edit-image" id="edit-image-1">Edit This Area</div>');
});
});
This code dynamically inserts a div class="edit-image"
into each div class="callout"
What I want to do is retreive the ID (numeric portion) from div class="callout"
and dynamically insert it into the ID of div class="edit-image"
I am having trouble with this, can anyone help?
Answer by Starx
You can use .split() method of Javascript. It should look something like this
$('#portal').find('.callout').each(function(k,v) {
id = $(this).attr("id");
//take out the id of element
temp = id.split("-");
//split the string based on "-"
idnum = temp[1];
//take the second part of split i.e the integer part
$(this).append('<div class="edit-image" id="edit-image-'+idnum+'">Edit This Area</div>');
//then finally use it
});
Here is a working demo