开发者

How to get full descendant hiearchy?

Given a parent, how can i get its descendants so that their hierarchy is kept.

parent > des1 > des2 > des3

parent.find('*') simply retur开发者_C百科ns not in order, it gives

find('des1, des2. des3') 

what I expect was

find('des1 des2 des3')


There are lots of ways to traverse using jQuery. Here's one approach. I'm using the following markup:

<div id="demoParent">
  <div id="des1">
    <div id="des2"> 
      <div id="des3">
        hello world
      </div>
    </div>
  </div>
</div>

I use this recursive function to traverse down and return a string with the hierarchy:

function getHierarchy(selector) {
    // temp variable to hold the hierarchy as an array
    var hierarchy = [];
    // if selector element has a :first-child...
    while ($(selector).children(':first-child').length > 0) {
        // then push it into the array and then traverse into the :first-child
        hierarchy.push($(selector).children(':first-child').attr('id'));
        selector = $(selector).children(':first-child');
    }
    // when there are no more :first-child elements, return string
    // formatted like elemA > elemB > elemC > elemD
    return hierarchy.join(' > ');
}

When I call this code like this: alert(getHierarchy('#demoParent'));

I get this result as an alert: des1 > des2 > des3

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜