Hamman359
Hamman359

Reputation: 1052

Why am I losing my characters from my html string when trying to add html dynamically using javascript

I have a page that I am trying to dynamically add some links to. The links are getting added to the page fine, but the '[' and ']' at either end of the line are getting dropped. The code from my .js file is:

var html = "[ <a href='#'>Change</a>&nbsp;|&nbsp;<a href='#'>Remove </a> ]";
$(html).appendTo("#id123");

The result I want is:

[ <a href='#'>Change</a>&nbsp;|&nbsp;<a href='#'>Remove</a> ]

The result I'm getting is:

<a href='#'>Change</a>&nbsp;|&nbsp;<a href='#'>Remove</a>

If I wrap the line in a <span> tag like so:

var html = "<span>[ <a href='#'>Change</a>&nbsp;|&nbsp;<a href='#'>Remove </a> ]</span>";
$(html).appendTo("#id123");

it renders as expected. I set a breakpoint on the code and checked the html var right before the .appendTo and it contains the '[' and ']'.

Anyone know why this is happening? Are '[' and ']' special character that need escaped and I'm just forgetting that fact?

Upvotes: 2

Views: 136

Answers (3)

RussellUresti
RussellUresti

Reputation: 6221

When you wrap your html variable inside of "$()", it creates a jQuery object out of it. That object removes anything that's outside of a markup tag (like <a> or <span>). You can take out the"[" and put "TESTING THIS" in it's place and you'll see it still won't show up.

So that's why you're losing it in your output.

Upvotes: 3

Fletcher Moore
Fletcher Moore

Reputation: 13814

I'm not sure why this happens. It seems like something internal to the appendTo() I tried it with append() and it worked out fine. So you could write $("#id123").append(html)

Upvotes: 0

Tejs
Tejs

Reputation: 41266

No, those are just not valid XHTML. If you put the '[' and ']' in their own spans, like so:

 "<span>[&nbsp;</span><a href='#'>Change</a>&nbsp;|&nbsp;<a href='#'>Remove </a></span>&nbsp;]</span>"

You would also get your expected text. jQuery will parse and create valid HTML, and the brackets aren't contained in an element.

Upvotes: 2

Related Questions