Austin
Austin

Reputation: 3080

Converting String to HTML - string to "a href" element

I am having some trouble getting some HTML links to add to my HTML page. I have tried searching around but nothing has helped thus far.

My page will initially load a snippet:

<div style="display: inline-block; color: rgb(0, 255, 144)">Roster: </div>
<span id="teamRoster"></span>
<br />

Which appears like Roster: in the View

Right now my snippet has been modified to add names:

var rosterListings = "";
for (var i = 0; i < teamRoster.length; i++) {
    rosterListings = rosterListings + teamRoster[i] + ", ";
}
$("#teamRoster").text(rosterListings);

Which will update my View to Roster: John, Frank, Susan, etc..

However, I am trying to now add <a href> tags around each person and turn them all into actual links. My attempt looks like this

var rosterListings = "";
    for (var i = 0; i < teamRoster.length; i++) {
        rosterListings = rosterListings + " <a href='" + idList[i] + "'>" + teamRoster[i] + "</a>,";
    }
    $("#teamRoster").text(rosterListings);

which displays as

Roster: <a href='#'>John</a>, <a href='#'>Frank</a>, etc..

I understand why this occurring since I am setting actual text/strings, but is there a way to convert this string into HTML elements? I have tried a few $.parseHTML code snippets that I found from Googling but I must be implementing them all wrong.

Upvotes: 5

Views: 8158

Answers (3)

AstroCB
AstroCB

Reputation: 12367

The problem is that you're using .text(), which will insert only text into the span, as seen here.

You need to use .html() if you want what is inserted to actually render as HTML.

So, try this:

$("#teamRoster").html(rosterListings);

Demo

Also note that the way you've set up your for loop causes an extra comma to be placed at the end of the list; I've fixed that here by checking whether it's the last element:

if (i !== teamRoster.length - 1) {
        rosterListings = rosterListings + " <a href='" + idList[i] + "'>" + teamRoster[i] + "</a>,";
} else {
        rosterListings = rosterListings + " and <a href='" + idList[i] + "'>" + teamRoster[i] + "</a>.";
}

Upvotes: 2

Just code
Just code

Reputation: 13801

Well, solution is quite obvious

Just replace

 $("#teamRoster").text(rosterListings); 

With:

$("#teamRoster").html(rosterListings);

Because if you use it as a text then it will treat it as the text and if you write html then it will treat it as a html

Upvotes: 5

mtyson
mtyson

Reputation: 8580

As Just code points out, you want to use the html method, not the text method. html() is jQuery's wrapper for innerHTML, which injects the string as html.

Here is a jsFiddle showing the difference:

http://jsfiddle.net/89nxt/

$("#teamRosterHtml").html("<a href='#'>John</a> <a href='#'>Frank</a>");
$("#teamRosterText").text("<a href='#'>John</a> <a href='#'>Frank</a>");

Upvotes: 0

Related Questions