Klemola
Klemola

Reputation: 91

Escaping a jQuery append string to use a variable as "href" target and inside and element

I am building a script that generates a table of content (as ) of the headings (currently only ) on a page.

I am having trouble with appending elements without an id, because I want to assign a href target to a link, and use a variable as the link's content.

The code that I am working on:

        var h_num; // introduce the running id counter
        $("h2").each(function (i) {
            // retrieve the text contained in the element
            $h_content = $(this).text();
            // add a running id to the h2
            $(this).attr("id", ("h2_"+i));
            // the id attribute value that was just added to the element
            $h_num = ("h2_"+i);
            $new_id = ("#" + $h_num);
            console.log($h_num, "hoonum", $new_id, "newid"); //for debugging
            // append a <li> element with a link to the heading 
            $('#toc ol').append(
                '<li>' + '<a href="$h_num">$h_content'
            );
        });    

So I can't find a way to escape the line inside the append function.

$h_content is the title of the heading (to be included as the text for the link to the heading), and $new_id is the href target id.

I would like the table of content's markup to look like this

<ol>
    <li><a href="#h2_0">First heading topic</a></li>
    <li><a href="#h2_1">Second heading topic</a></li>
</ol>   

Upvotes: 1

Views: 196

Answers (1)

uadnal
uadnal

Reputation: 11445

For performance purposes, you should append to a documentFragement first.

    var frag = document.createDocumentFragment();
    $("h2").each(function (i, el) {
        var li = document.createElement( "li" );
        var $a = $("<a>", { id: "h2_" + i }).text( $(el).text() );
        li.appendChild( $a[0] )
        frag.appendChild( li );
    });
    $("ol").append(frag);
​

http://jsfiddle.net/landau/RyeAA/

http://jsfiddle.net/landau/RyeAA/5/ - Updated version

Upvotes: 3

Related Questions