JQuery get parent element

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

(parent content)

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

Products:

        <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
source share
2 answers
$(this).parents('li:has(ul)').children('div:first').text();

This will go to the nearest <li>one that has a sub <ul>, and then to its first child <div>and get the text.

This will also get text when you are in the top element <li>. Is desirable? If not, just add .parent()as follows:

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

, <li>.

+3

" 1.1" <li>, :

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

.parent() :

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

.parent() <li> 2nd, <ul>, <li> .find('div') <div>Item 2</div>

+3

Source: https://habr.com/ru/post/1763371/


All Articles