Eric Eric - 21 days ago 8
jQuery Question

Use JQuery to build an anchor

I want to use jquery to build HTML like this:

<li><a href="#"><span class="play"></span><span class="trackName">Track Name</span></a></li>


It seems simple but I can't figure it out how to include HTML tags as part of my anchor text.

If I use something like:

$("<a />", { text: $('<SPAN class="play" />') + "Track Name" })


then the span tags get escaped.

Answer Source

There are several ways to do it, including (but not limited to):

// one big string
$('<a href="#"><span class="play"></span><span class="trackName">Track Name</span></a>')

// create <a> then append() the span
$('<a></a>').attr("href","#")
            .append('<span class="play"></span><span class="trackName">Track Name</span>');

// create <a> then set all of its contents with html()
$('<a></a>').attr("href","#")
            .html('<span class="play"></span><span class="trackName">Track Name</span>');

// append spans created earlier:
var spans = $('<span class="play"></span><span class="trackName">Track Name</span>');
var a = $('<a></a>').append(spans);

Note that .html() replaces any and all existing contents, while .append() adds to the end. So given that you have two span elements in your example you could create those independently and append them one at a time:

$('<a href="#"></a>').append('<span class="play"></span>')
                     .append('<span class="trackName">Track Name</span>');