user1747525
user1747525

Reputation: 13

jQuery iterate through HTML and create tabs on the fly?

I have a slight problem with creating a tabbed interface. We are using a system that have a product's content in only one text field when added to the catalogue. So the HTML markup looks like this, and can have both p and ul (even table) elements as content (no classes or id's can be added unfortunately):

<div class="productDesc">
   <h1>Content 1</h1>
   <p>Content 1 content</p>

   <h1>Content 2</h1>
   <ul>
     <li>Content 2 content #1</li>
     <li>Content 2 content #2</li>
     <li>Content 2 content #3</li>
   </ul>

   <h1>Content 3</h1>
   <p>Content 3 content #1</p>
   <p>Content 3 content #2</p>
   <p>Content 3 content #3</p>
</div>

What I would like to be able to do is create a tabbed interface, so that each H1 element is a tab, and it's content of course the content that should be displayed when the tab is clicked.

Is there a way to iterate through the HTML to get the end result looking like this for example:

<div id="tabs">
   <ul class="productTabs">
      <li><a href="#Content1">Content 1</a></li>
      <li><a href="#Content2">Content 2</a></li>
      <li><a href="#Content3">Content 3</a></li>
   </ul>
</div>

<div id="productDesc">
   <div id="Content1">
      <p>Content 1 content</p>
   </div>
   <div id="Content2">
      <ul>
         <li>Content 2 content #1</li>
         <li>Content 2 content #2</li>
         <li>Content 2 content #3</li>
      </ul>
   </div>
   <div id="Content3">
      <p>Content 3 content #1</p>
      <p>Content 3 content #2</p>
      <p>Content 3 content #3</p>
   </div>
</div>

Once I get the HTML markup fixed I should be able to make the tabs working.

Upvotes: 1

Views: 420

Answers (2)

mechanicalfish
mechanicalfish

Reputation: 12826

If you absolutely cannot change the generated markup:

var productDesc = $('div.productDesc');
var newProductDesc = $('<div/>').attr('id', 'productDesc');
var tabs = $('<div/>').attr('id', 'tabs').insertBefore(productDesc);
var productTabs = $('<ul/>').addClass('productTabs').appendTo(tabs);

var i = 0;
var lastTabContent;
productDesc.children().each(function() {
    if($(this).is('h1')) {
        i++;
        $('<li/>').appendTo(productTabs).append($('<a/>').attr('href', '#Content' + i).html($(this).html()));
        lastTabContent = $('<div/>').attr('id', 'Content' + i).appendTo(newProductDesc);
    } else {
        $(this).appendTo(lastTabContent);
    }
});
productDesc.replaceWith(newProductDesc);

jsfiddle

Upvotes: 1

Anshu
Anshu

Reputation: 7853

If you wish to convert the HTML markup, I would recommend you to use XSLT. Change the HTML markup and probably use jQuery tab plugin for tabs

Upvotes: 0

Related Questions