Saturday, March 31, 2018

Get all html tags(parent and child tags) with id and class name with Javascript/JQuery



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





  1. head->title

  2. 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("*");

});


Live example



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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...