o_O
o_O

Reputation: 5737

JQUery find and match parent based on a dynamic child class

Ok it's a little hard to explain in a single title but basically I have a dynamic class added to a child element based on it's parent's dynamic class. Added so:

$('ul').each(function(key){
    if ($(this).hasClass('sortable')){
        $(this).addClass('parent' + key);
        $(this).children().addClass('parent' + key);
    };
});

The structure is pretty simple after this:

<ul class="parent0">
    <li class="parent0">
        <ul class="parent1">
            <li class="parent1"></li>
        </ul>
    </li>
</ul>

Now the UI has the user move these li outside of the parent and placed elsewhere. Later on, I want to check the element and then match it to it's corresponding (original) parent. It can't be $(this) parent because it will be moved out of the parent but the classes still remain.

So the check is looking for .parent(n) and then finding the ul with .parent(n) eventually this code will live inside:

$('sortable li').appendTo($('THIS-IS-THE-DYNAMIC-CLASS'));

So I'm assuming the find will be before this but I don't know how to write that.

Upvotes: 0

Views: 475

Answers (1)

Eli Gassert
Eli Gassert

Reputation: 9763

I would use a different attribute other than class so it can be wholly unique. Either use $(this).data or $(this).attr. And I would recommend assigning IDs to the parent (or a different attribute) that, again, can be wholly unique. This will keep things cleaner in my opinion.

For example...

Assuming:

$(this).attr('parentClass', '.parent' + key);

then

$('.sortable li').each(function() { $(this).appendTo($(this).attr('parentClass')); });

Upvotes: 1

Related Questions