I have a DOM
:
<body>
<div>
<h1 id="header1">home1</h1>
<a id="link1">link1</a>
<p id="para1">things1</p>
</div>
<span>
<h1 id="header2">home2</h1>
<a id="link2">link2</a>
<p id="para2">para2</p>
</span>
</body>
I want to index this to JSON
like:
{
"body": {
"div": [
{
"h1": "header1",
"a": "link1",
"p": "para1"
}
],
"span": [
{
"h1": "header2",
"a": "link2",
"p": "para2"
}
]
}
}
I've tried this:
function indexELEMS()
{
listy = $("*[id]").map(function(){
outy = this.tagName+":"+this.id;
return outy;
}).get();
DOMobj = $.extend({}, listy);
console.log(DOMobj);
}
But I get something like this:
0:"h1:home"
1:"a:link1"
2:"p:things1"
Understandable, I've just told the function to do that.
But if I try it on just the h1
's like this:
function indexELEMS()
{
outy = {};
listy = $("h1[id]").map(function(){
outy.h1s = this.tagName+":"+this.id;
return outy;
}).get();
DOMobj = $.extend({}, listy);
console.log(DOMobj);
}
It will overwrite the outy.h1s
with the last one, how do I add it to the (JSON)object?
Or better yet, how do I get the whole document element structure output in nice JSON form?
I could do: $('document > body > div > h1').attr('id')
every time, but that's pretty inefficient and resource intensive, I want to cache all the elements and then read them out, and when they change, (maybe I'll watch the object with .watch
), or is added in the object, create an element in the appropriate position.
Or is there a better way get an overview of which elements have ID
s (and check if that ID
is duplicate or not), some native function?
I'm also afraid that the JSON Object won't allow multiple div:
entries?
Or should I just go for the jQuery selector completely and stop whining about efficiency?
(edit: Ok, the multiple div part is maybe not possible, or can't I access the second one with .div[1] ?)
So, my main question would be, if you take the indexELEMS function, how can I get an object that is accesibly by:
DOMobj.body.div.h1
So I can do an If ==
on it, or cycle through it with div.[index]
in a $.each
loop
I would think, cycling through DOMobj.body[index] instead of $(''), oh wait, can I actually access the object created from $('')? like .body? It can't be that easy..