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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!