Does anybody knows how can I get all the HTML tags that exist in a page?
var items = document.getElementsByTagName("*");
This will get all the tags, but my requirement is
- get a first parent tag and all the child tags under it
- get the next parent tag and all the child tags under it and so on
I need to get the tags in a kind of tree-structure. Prefer to do that with Javascript or JQuery.
For example:
Example Page
Blabla
Should Return:
html
- head->title
- body-->h1,(div-->table-->tr-->td,td)
Answer
document.documentElement
is the root of the tree (html
). You can then get all of its child elements via children
(childNodes
would include non-Element children), and get their descendants in document order using querySelectorAll("*")
:
var results = Array.prototype.map.call(
document.documentElement.children,
function(element) {
return element.querySelectorAll("*");
});
results
will be an array with an entry for each direct child of the html
element, where each element is a NodeList
. If you want an array of arrays, you can use Array.from
on the result of querySelectorAll
(polyfilling it if necessary, as it's relatively new).
Of course there are a dozen ways to spin this. For instance, an array of objects instead:
var results = Array.prototype.map.call(
document.documentElement.children,
function(element) {
return {
element: element,
descendants: Array.from(element.querySelectorAll("*"))
};
});
No comments:
Post a Comment