1

I'm trying to modify a JavaScript template such that each of the words in a particular string are wrapped in <span> elements. I have:

<% var tagString = "Happy Sad Up Down", tags = tagString.split(" "), wrappedTags = ""; %>
<% for (var i = 0; i < tags.length; i++) { %>
    <% wrappedTags += "<span>" + tags[i] + "</span>"; %>
<% } %>
<p><%=wrappedTags%></p>

The problem is that this outputs the "<span>" and "</span>" as text, not HTML, so I end up with the following text being displayed on the page:

<span>Happy</span><span>Sad</span><span>Up</span><span>Down</span>

Is there any way within this syntax to output the wrapping <span> tags as HTML?


UPDATE: with regular (non-template) syntax, it works if I simply write wrappedTags to the page: http://jsfiddle.net/4QtUd/. However, I can't figure out the equivalent way to do this within the template syntax.

1
  • What template framework are you using? Commented Oct 23, 2012 at 20:05

2 Answers 2

1

You could do something like this, outputting it directly within the loop.

<% var tagString = "Happy Sad Up Down", tags = tagString.split(" "); %>
<p>
<% for (var i = 0; i < tags.length; i++) { %>
    <span><%= tags[i] %></span>
<% } %>
</p>
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! That's so obvious now, haha.
0

Try replacing your < and >with HTML entities. http://www.w3schools.com/html/html_entities.asp

So basically: < -> &lt; and > -> &gt;

1 Comment

That still outputs as text, so I get "&lt;span&gt;Happy&lt;/span&gt;", etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.