Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Remove a Surrounding DIV with jQuery?

Tags:

html

jquery

css

In Wikispaces, when you add a Table of Contents to the Main Content area, any heading (h1-h6) you use within that main content area is automatically placed within the table of contents, and serves as an anchor link that when clicked on, takes you down the page to the heading referenced from the table of contents.

By default, wikispaces surrounds the anchor links within the table of contents with a div, which depending upon the heading you're using within the main content area (h1-h6), it applies a greater left margin to it. Here's the markup of the table of contents of only h2 headings...

<div style="margin-left: 2em;"><a href="#toc1">Hello there</a></div>
<div style="margin-left: 2em;"><a href="#toc2">How are you?</a></div>
<div style="margin-left: 2em;"><a href="#toc3">Here's an External Link</a></div>
<div style="margin-left: 2em;"><a href="#toc4">Here's an Example Heading</a></div>
<div style="margin-left: 2em;"><a href="#toc5">Here's an Even Longer Example Heading</a></div>

I'd like to completely remove the ugly and unnecessary embedded CSS styling DIV's, and wrap the table of contents with an unordered list, with the anchor links wrapped with list items. So using jQuery, the markup above would be transformed to more semantic markup... an unordered list.

<ul>
<li><a href="#toc1">Hello there</a></li>
<li><a href="#toc2">How are you?</a></li>
<li><a href="#toc3">Here's an External Link</a></li>
<li><a href="#toc4">Here's an Example Heading</a></li>
<li><a href="#toc5">Here's an Even Longer Example Heading</a></li>
</ul>

The jQuery should compensate for how ever many headings the user might place within the main content area. So basically, no matter what, the table of contents will always be wrapped with an unordered list, regardless of how many list items there are...

Thanks for your help!

like image 932
Spencer B. Avatar asked Feb 27 '23 19:02

Spencer B.


1 Answers

Something like this should work:

// Insert a UL after the h1 tag
var $ul = $("<ul></ul>").insertAfter($("div#toc > h1"));

// Find all the toc links
$("a[href^=#toc]").each(function(){
    var $li = $("<li></li>"),
        $parent = $(this).parent();

    // Append auto deletes it from its old position
    $li.append(this);

    // Remove the empty div
    $parent.remove();

    // Add the li to the ul
    $ul.append($li);
})
like image 178
Doug Neiner Avatar answered Mar 08 '23 08:03

Doug Neiner