Link to home
Start Free TrialLog in
Avatar of CAS-IT
CAS-IT

asked on

JavaScript or JQuery display HTML as tree

Hi,

I'm looking for some JavaScript or JQuery that will display an HTML object's tree, giving the tag names and what html/text the child nodes contain. JavaScript or JQuery doesn't matter to me, so it can start with $("myDiv") or document.getElementById("myDiv").

Basically, if I start with:

<div>
  <p>Hello! My Name is <b>Bob!</b>. You can e-mail me at <a href="mailto:bob@bob.com">Bob AT bob DOT com</a> </p>
</div>

Then I want to print something like ...

Tag1: p : Hello! My Name is <b>Bob!</b>. You can e-mail me at <a href="mailto:bob@bob.com">Bob AT bob DOT com</a>.
Tag2: b : Bob!
Tag3: a : Bob AT bob DOT com

And, the ultimate goal is only to print elements that have no children, i.e. 2 and 3. But once I get this started I think I can take it there.

Here's what I've started with, and it DOES NOT work. I'm hoping someone can help me.

function splode(theObject) {
  if ($(theObject).children().size() >= 1) {
    $(theObject).children().each(function(){
      console.log("[RecurseLevel] " + i + ": " + $(this).tagName);
      i = i + 1;
      splode($(this));
    });
  }
  else {
    console.log("[ChildLevel] " + i + ": " + $(theObject).tagName);
    i = i + 1;
  }
}

$("#myDiv").children().each(function(){
    console.log("[TopLevel] " + i + ": " + $(this).html());
    i = i + 1;
    splode($(this));
});



Basically, that only gets me output at [TopLevel] - I never see anything at [ChildLevel] or [RecurseLevel].

And tagName doesn't ever work, even at the top level. Don't know why.
ASKER CERTIFIED SOLUTION
Avatar of zappafan2k2
zappafan2k2

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of CAS-IT
CAS-IT

ASKER

Accepted my own comment (partially) because zappanfan's code only showed a way to reference an element's children, not print them.