Search code examples
jqueryvariablesappendcloneattr

jQuery copy HTML elment and add value to all children IDs


interesting one. i'm working on a big, modular form that the user can add or remove services in and need to reach into the DOM, copy an HTML element, and add a value to the end of both it and it's children's ID's.

So for example:

<li id="serviceModule" class="serviceModule">
    <ol>
        <li id="subModuleTypeA">subModule</li>
        <li id="subModuleTypeB">
            <ol>
                <li id="subModuleTypeASubModuleX">subSubModule</li>
                <li id="subModuleTypeASubModuleY">subSubModule</li>
                <li id="subModuleTypeASubModuleZ">subSubModule</li>
            </ol>
        </li>
        <li id="subModuleTypeC">subModule</li>
    </ol>
</li>

Would become:

<li id="serviceModule1" class="serviceModule">
    <ol>
        <li id="subModuleTypeA1">subModule</li>
        <li id="subModuleTypeB1">
            <ol>
                <li id="subModuleTypeASubModuleX1">subSubModule</li>
                <li id="subModuleTypeASubModuleY1">subSubModule</li>
                <li id="subModuleTypeASubModuleZ1">subSubModule</li>
            </ol>
        </li>
        <li id="subModuleTypeC1">subModule</li>
    </ol>
</li>

Method that adds value:

$.fn.valulator = function(magic){

    var thiis = $(this),
        el,
        id;

    thiis.add(thiis.children()).each(function(){

        el = $(this);
        id = el.attr('id');

        el.attr('id', id + magic);
    });

    return this;
};

Binding that triggers valulator:

$add.click(function(event){

    event.preventDefault();

    $index = $index + 1;
    $('.serviceModule')
        .clone()
        .valulator($index)
        .appendTo('#services');
});

Thanks for your help! Here's a jsFiddle: http://jsfiddle.net/phqvr/3/


UPDATE

Finding that the first issue i'm running into within valulator() is that children() only brings up direct descendants.. instead i need to search ALL elements.


Solution

  • Got it; there were two issues.

    1) as mentioned in the update, children() only traversed one level down- reworked it to:

    thiis.find('*').andSelf().each()
    

    2) in my Fiddle, there was an added conditional if(el[id]) that would always fail. replaced with below code to prevent additions to elements that didn't have ID's to begin with:

    if (id){}
    

    Full working code here: http://jsfiddle.net/phqvr/4/

        $.fn.valulator = function(magic){
    
            var thiis = $(this),
                el,
                id;
    
            thiis.find('*').andSelf().each(function(){
    
                el = $(this);
                id = el.attr('id');            
    
                if (id){
    
                    el.attr('id', id + magic);
                }
            });
    
            return this;
        };