简体   繁体   中英

How to get all decendant li of ul even under another ul

how can i get "all" attr("class") of li under ul#div and return it as array with out repeating same value of class?

<ul id="div">
  <li class="a"></li>
  <li class="aa">
    <ul id="set">
      <li class="aa1"></li>
      <li class="aa2"></li>
    </ul>
  </li>
  <li class="aaa"></li>
  <li class="aaa"></li>
  <li class="aaa"></li>
  <li class="a"></li>  
</ul>

im looking for return like this:

return class in array(a,aa,aa1,aa2,aaa)

Get all <li> descendants of <ul> that have a class attribute, make it into a standard array, then get classes of each one.

 var classes = $('ul li[class]').toArray().map(function(el) { return el.className }); console.log(classes);
 <!-- results pane console output; see http://meta.stackexchange.com/a/242491 --> <script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul id="div"> <li class="a"></li> <li class="aa"> <ul id="set"> <li class="aa1"></li> <li class="aa2"></li> </ul> </li> <li class="aaa"></li> <li class="aaa"></li> <li class="aaa"></li> <li class="a"></li> </ul>

With pure JavaScript, you could do something like this

var node = document.getElementById("div");
var children = node.childNodes;
var output = [];
for (var i = 0; i < children.length; i++)
{
    if (typeof children[i].className !== "undefined")
        output.push(children[i].className);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM