Saturday 31 March 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

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...