开发者

jQuery get item parent

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&开发者_如何学Cgt;
            <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);


        }


$(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>.


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>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜