Il y a beaucoup de façons de traverse utilisant jQuery. Voici une approche. J'utilise le balisage suivant:
<div id="demoParent">
<div id="des1">
<div id="des2">
<div id="des3">
hello world
</div>
</div>
</div>
</div>
J'utilise cette fonction récursive pour traverser vers le bas et retourner une chaîne avec la hiérarchie:
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(' > ');
}
Quand j'appelle ce code comme ceci: alert(getHierarchy('#demoParent'));
Je reçois ce résultat en alerte: des1 > des2 > des3