Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use JQuery to build an anchor

Tags:

jquery

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.

like image 226
Eric Avatar asked Feb 16 '12 01:02

Eric


People also ask

How to append anchor tag in jQuery?

With jQuery, you can use the . append() method to append the anchor tag at the end of the specified div element.

Can we use Onclick in anchor tag?

It is safe to click on that link with # href; the page does leave/reload url. Follow the above advice with caution, as HTML5 rules explicitly state that href="#" is supposed to navigate to the top of the page. You can simply add the href attibute without content, and get the click behaviour.


3 Answers

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>');
like image 139
nnnnnn Avatar answered Oct 21 '22 11:10

nnnnnn


Drop the internal jQuery constructor:

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

jsFiddle.

or, if you want the code as HTML in the link:

$("<a />", { html: '<SPAN class="play" /> Track Name' });
like image 27
alex Avatar answered Oct 21 '22 13:10

alex


var link = $("<a>");
    link.attr("href","http://www.google.com");
    link.attr("title","Google.com");
    link.text("Google");
    link.addClass("link");
like image 34
Vicky Avatar answered Oct 21 '22 13:10

Vicky