Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
            <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);


        }
like image 619
Andy Fleming Avatar asked Apr 18 '26 11:04

Andy Fleming


2 Answers

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

like image 113
user113716 Avatar answered Apr 20 '26 00:04

user113716


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>

like image 39
Crayon Violent Avatar answered Apr 20 '26 01:04

Crayon Violent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!