In Order Traversal Of Html Tags - How Can I Do This?
I am trying to iterate over HTML dom. I need to print the tag names as it occurs i.e. in order. The following code does traverse the HTML fine, but it does not print the HTML nodes
Solution 1:
I have created an example that might help you.At first you retrieve all tags from DOM. Using a loop you get the node list of the requested tag and then you print the tags. You should use nextSibling
to print em
because it's inside the p
tag.
const el = $("html > body");
let temp = el[0].childNodes[0].nextSibling;
while(temp){
console.log("->"+temp.nodeName);
if(temp.childNodes.length != 0){
for(let i=0;i<temp.childNodes.length;i++){
let node_name = temp.childNodes[i].nextSibling != null ? temp.childNodes[i].nextSibling : null;
console.log(" "+temp.childNodes[i].textContent);
if(node_name != null){
console.log(" -"+node_name.parentElement.tagName);
if(node_name.tagName != undefined){
console.log(" -"+node_name.tagName);
}
}
}
}
temp = temp.nextSibling;
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><p> this is a p tag <em> this em tag </em> closing p tag </p>
Post a Comment for "In Order Traversal Of Html Tags - How Can I Do This?"