views:

225

answers:

2

I basically have several divs each with ids "id_1", "id_2" "id_3" etc. The divs are all initially empty.

I want on page load to populate all the divs with certain html content. But the part that has been troubling me is that I also need to extract the unique id portion for use within the html:

<div id="id_3">
     <div id="inner_3></div>
</div>

where the inner div is what gets printed. Notice that the '3' is extracted from the container div id by the javascript and then subsequently used and printed in the inner div.

Any ideas how to do this with jquery? Thanks in advance.

+1  A: 

You can fetch all the div elements that have an id that starts with a certain string:

$(function() {
    $('div[id^=id_]').each(function() {
        var id = $(this).attr('id').split('_').pop();
        $(this).html(
            $('<div/>').attr('id','inner_' + id)
        );
    });
});

Then you loop through each, get the id, and do your HTML manipulation.

Paolo Bergantino
excellent! exactly what I needed. Thanks!
A: 

there are several ways of doing this, but in the end its just simple string manipulation. Here is an example:

// on page load
$(function(){
    //find all divs and iterate through them - you can use any selector you like
    $("div").each(function(){
        //this gets the id attribute of the div we are currently on in the loop
        var id = $(this).attr("id");
        //this gets the number at the end - notice that its just string manipulation
        var nid = id.slice(id.lastIndexOf("_") + 1)
        //create inner div, give it an id and append
        var innerDiv = $('div').attr("id", "inner_" + nid);
        $(this).append(innerDiv);
        //all done - you can append content to inner div here
        // innerDiv.append(someContent);
    });
});
Darko Z