Arman
Arman

Reputation: 4636

Jquery making "content" based on h1 h2 h3 tags

I would like to add a content before some div which has several sections and sub sections.

Can I parse it on fly using jquery?

For example I would like to have some thing like:

<div id="cont"></div>
<div id="help-area">
<h1>Head1</h1>
   ...
   ...
 <h3>Subsection1</h3>
    ....
    ....
</div>

As an output I would like to have:

<div id="cont">
 <ul>
  <li>Head1
     <ul>
       <li>Subsection1</li>
     </ul> 
  </li>
  ....
 </ul>
</div>
<div id="help-area">
<h1>Head1</h1>
   ...
   ...
 <h3>Subsection1</h3>
    ....
    ....
</div>

Can I achieve it using jquery or I should parse it by PHP?

Thanks in advance. Arman.

Upvotes: 3

Views: 676

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1075139

You can do it with jQuery, but of course that would mean that anyone accessing the page without JavaScript enabled wouldn't have access to the table of contents. Not ideal.

But something along these lines:

jQuery(function($) {

  var ul = null;
  var lasth1 = null;
  var lasth1ul = null;
  var lasth2 = null;
  var lasth2ul = null;

  $("h1, h2, h3").each(function() {

    switch (this.tagName.toLowerCase()) {
      case "h1":
        if (!ul) {
          ul = $("<ul>");
        }
        lasth1 = $("<li>").html($(this).html()).appendTo(ul);
        lasth1ul = null;
        lasth2ul = null;
        break;
      case "h2":
        if (!lasth1) {
          // Deal with invalid condition, h2 with no h1 before it
        }
        else {
          if (!lasth1ul) {
            lasth1ul = $("<ul>").appendTo(lasth1);
          }
          lasth2 = $("<li>").html($(this).html()).appendTo(lasth1ul);
        }
        break;
      case "h3":
        if (!lasth2) {
          // Deal with invalid condition, h3 with no h2 before it
        }
        else {
          if (!lasth2ul) {
            lasth2ul = $("<ul>").appendTo(lasth2);
          }
          $("<li>").html($(this).html()).appendTo(lasth2ul);
        }
        break;
    }

  });
  if (ul) {
    $("#cont").append(ul);
  }

});

Live example

Note that jQuery guarantees that you'll receive the matched elements in document order.

The above is just one way to do it. You could also use a recursive descent approach, but for just three levels the above is simple and doesn't repeat itself that much...

Upvotes: 4

Nikhil
Nikhil

Reputation: 3384

Of course you can. If you access to to content you want to show then all you do is use the "append" and "prepend" functions of jQuery. As a quick demo, check this

$("#cont").append("<ul><li>Head1<ul><li>Subsection1</li></ul></li></ul>")

Upvotes: -1

Related Questions