root66
root66

Reputation: 607

jQuery: find descendants and get selector path

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>

Upvotes: 1

Views: 126

Answers (1)

Rino Raj
Rino Raj

Reputation: 6264

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>

Upvotes: 1

Related Questions