Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing attributes of cloned elements using CSS selectors

Tags:

html

jquery

I am trying to clone an element, and then traverse through it's child elements and change attributes accordingly, the thing is that I am trying to access the elements via custom attributes using CSS selectors and I can't seem to get it to work, here is what I have thus far,

HTML:

<div id='main_container'>
    <div id="container">
        <div class="wrapper">
            <div><label>... </label></div>
            <div><input type="text" id="one" new="one_1" /></div>
        </div>
        <div class="wrapper">
            <div><label>... </label></div>
            <div>
                <select id="two" new="two_1" >
                    <option>...</option>
                    <option>...</option>
                </select>
            </div>
        </div>
        <div class="wrapper">
            <div><label>... </label></div>
            <div>
                <select id="three" new="three_1" >
                    <option>...</option>
                    <option>...</option>
                </select>
            </div>
        </div>
    </div>

    <div class="wrapper">
        <input type="button" value="add a section" id="button" />
    </div>
</div>

jQuery:

    $('#button').click(function(){
        var clone = $('#container').clone().appendTo('#main_container');

        clone.children('["new*=one"]').attr('class', 'one');
        clone.children('["new*=two"]').attr('class', 'two');
        clone.children('["new*=three"]').attr('class', 'three');
    });
like image 772
Odyss3us Avatar asked Dec 04 '22 11:12

Odyss3us


1 Answers

.children() only gets immediate or direct children, you're looking for .find() here, like this:

$('#button').click(function(){
    var clone = $('#container').clone().appendTo('#main_container');

    clone.find('[new*="one"]').attr('class', 'one');
    clone.find('[new*="two"]').attr('class', 'two');
    clone.find('[new*="three"]').attr('class', 'three');
});

You can give it a try here.

Note the moved quotes above as well. .find() searches any level deep, so all descendants when matching the selector, that's the important difference in this case. Also, to be safe on the attribute though, I'd use data-new instead, it'll be HTML5 compliant as well.

Another thing to keep in mind is with the code you posted, you're getting duplicate IDs, make sure to remove or change those when cloning.

like image 82
Nick Craver Avatar answered Dec 06 '22 00:12

Nick Craver