views:

40

answers:

2

I am trying to get the parent item of an item with the below code.

(the content of the parent)

ex. the parent of "Item 1.1" would be "Item 2" in the below example.

Items:

        <ul class="sortable" id="page-list">

            <li><div>Item 1</div></li>
            <li><div>Item 2</div>
                <ul>
                    <li><div>Sub Item 1.1</div></li>
                    <li><div>Sub Item 1.2</div></li>
                    <li><div>Sub Item 1.3</div></li>
                    <li><div>Sub Item 1.4</div></li>
                </ul>
            </li>

        </ul>

Javascript:

            function saveNewList() {
            //get DIV contents in order
            var divContents = [];
            $("ul.sortable > li div").each(function() { divContents.push($(this).text()) });
            var quotedCSV = '"' + divContents.join('", "') + '"';
            $("#results").text(quotedCSV);
            //get DIV parents' contents in order
            var divParents = [];
            // something needs to go here...
            var quotedCSVparents = '"' + divParents.join('", "') + '"';
            $("#results2").text(quotedCSVparents);


        }
+3  A: 
$(this).parents('li:has(ul)').children('div:first').text();

This will traverse up to the nearest <li> that has a sub <ul> then down to its first <div> child and get the text.

This would also get the text when you're in the upper <li> element. Is this desired? If not, just add a .parent() like this:

$(this).parent().parents('li:first').children('div:first').text();

This should avoid getting the text when you're not in the inner <li>.

patrick dw
divParents.push($(this).parent().parents('li:first').children('div:first').text()) worked beautifully!
DesignerGuy
@DesignerGuy - Glad it worked. Another approach with a little less traversing would be `$(this).closest('ul:not(.sortable)').prev().text()`.
patrick dw
+3  A: 

the parent of "Sub Item 1.1" is technically the <li> tag wrapped around it:

<li><div>Sub Item 1.1</div></li>

but you can use .parent() to move up a step in the hierarchy:

$([selector that targets <div>sub item 1.1</div>]).parent().parent().parent().find('div')

first .parent() takes you to the <li> 2nd one takes you to the <ul>, 3rd one takes you to the main <li> and .find('div') brings you back down to the <div>Item 2</div>

Crayon Violent
This would work from the sub item starting point, but you wouldn't want to use `.find('div')` after you get up to the parent. It will find all the nested `<div>` elements, including the Sub items, and return the text for all of them. Using `.children('div')` would work, though.
patrick dw