Search code examples
jqueryjquery-mobileclone

Jquery Clone object with all nested elements


I want to clone a JQM radio option and insert it at the end. The problem is clone() doesn't copy all the nested elements(dynamically generated). It just copies the first children not all the descendent. The generated content of radio option contains label element that has descendent elements too, but for some reason they don't clone.

Here is the fiddle http://jsfiddle.net/aSKBW/7/


Solution

  • .clone() is not truncating your selection, you are :). When you do this:

    new_option.find('label').text('Red');
    

    You are overwriting the HTML structure of the label element which looks like this:

    <label for="sky-color-2" data-theme="c" class="ui-btn ui-btn-icon-left ui-radio-off ui-corner-bottom ui-controlgroup-last ui-btn-up-c">
        <span class="ui-btn-inner ui-corner-bottom ui-controlgroup-last">
            <span class="ui-btn-text">Green</span>
            <span class="ui-icon ui-icon-radio-off ui-icon-shadow"></span>
        </span>
    </label>
    

    After you mess with the .text() function it looks like this:

    <label for="sky-color-2" data-theme="c" class="ui-btn ui-btn-icon-left ui-radio-off ui-corner-bottom ui-controlgroup-last ui-btn-up-c">Red</label>
    

    The fix is to target the .ui-btn-text element and change it's text:

    new_option.find('.ui-btn-text').text('Red');
    

    Here is an updated version of your JSFiddle: http://jsfiddle.net/aSKBW/13/

    Don't feel too bad, it's a very common mistake when getting used to jQuery Mobile and how it adds so much structure to the DOM.