1

I want to find all li.item descendants of ul.level-1:

$('ul.level-1').find('li.item')

and then get the full selector path like ul.level-1 > li > ul.level-2 > li > ul.level-3 > li.item, so I can pass this selector to a jQuery plugin, that accepts only strings.

Is there any function/plugin for finding the selector path?

<ul class="level-1">
  <li>I</li>
  <li>II
      <ul class="level-2">
        <li>A</li>
        <li>B
          <ul class="level-3">
            <li class="item">1</li>
            <li class="item">2</li>
            <li class="item">3</li>
          </ul>
        </li>
        <li>C</li>
      </ul>
   </li>
   <li>III</li>
</ul>
Rino Raj
  • 6,264
  • 2
  • 27
  • 42
root66
  • 477
  • 5
  • 17
  • Maybe to take a look here http://stackoverflow.com/questions/12644147/getting-element-path-for-selector – The Process Apr 07 '16 at 13:22
  • Looks interesting, but it gets the selector for a single element. In my example, find returns three li items, so the selector must take that into account. – root66 Apr 08 '16 at 09:23

1 Answers1

1

By using the below code you can extract the the value of the list element level by level.

Explanation

$('ul[class^="level-"]').each(function(e){ : This is used to loop all the ul with class starting with level-

$(this).find('>li').map(function(){.....}).get(); : This is used to loop through selected elements and getting the values to an array.

$(this).clone().children().remove().end().text() : This is used to retrieve only text not nested in child tags.

.replace(/[\n\r]+/g, '') : When we use the above explained selection it may have carriage return and space. So to remove that we are using this RegEx.

Working Demo

$(document).ready(function(){
    $('ul[class^="level-"]').each(function(e){
        var array = $(this).find('>li').map(function(){
          return $(this).clone().children().remove().end().text().replace(/[\n\r]+/g, ''); 
        }).get();
        console.log(array)
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="level-1">
  <li>I</li>
  <li>II
      <ul class="level-2">
        <li>A</li>
        <li>B
          <ul class="level-3">
            <li class="item">1</li>
            <li class="item">2</li>
            <li class="item">3</li>
          </ul>
        </li>
        <li>C</li>
      </ul>
   </li>
   <li>III</li>
</ul>
Rino Raj
  • 6,264
  • 2
  • 27
  • 42