I am parsing the DOM, and I want to extract the hierarchy of all elements that match a certain selector, lets say $('[data-node]')
, into a JavaScript object tree structure. I have failed to find a standard jQuery way of doing this. Using jQuery.find() seems to return a flat list. Perhaps I have just missed something obvious?
For example, I would like to parse this:
<div data-node="root">
<div class="insignificant-presentation">
<div>
<div data-node="interestingItem">
</div>
</div>
<div>
<div data-node="anotherInterestingItem">
<div data-node="usefulItem">
</div>
</div>
</div>
And create a structure in JavaScript like this:
[
{
"node": "root",
"children": [
{
"node": "interestingItem",
"children": []
},
{
"node": "anotherInterestingItem",
"children": [
{
"node": "usefulItem",
"children": []
}
]
}
]
}
]
Not sure why you'd need this, but something like this should do it
$.fn.tree = function() {
var arr = [],
self = this;
(function runForrestRun(el, arr) {
var isEl = self.is(el),
children = [];
if (isEl)
arr.push({
"node" : el.data('node'),
"children": children
});
el.children().each(function() {
runForrestRun($(this), isEl ? children : arr);
});
}(this.first(), arr));
return arr;
}
function createTree(root) { var children = []; root.find('div[data-node]').each(function() { // I can't think of a better way to not match the same ellement twice. if (!$(this).data('tagged')) { $(this).data('tagged', true); children.push(createTree($(this))); } }); return { "node": root.data('node'), "children": children }; } var tree = createTree($('div[data-node]').first()); document.write('<pre>' + JSON.stringify([tree], 0, 2))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div data-node="root"> <div class="insignificant-presentation"> <div> <div data-node="interestingItem"> </div> </div> <div> <div data-node="anotherInterestingItem"> <div data-node="usefulItem"> </div> </div> </div> </div> </div>
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.