Scott
Scott

Reputation: 2760

jQuery appendTo - prevent adding of closing tag

I am building an anchor tag as follows:

$('<a href="javascript: void(0)" xml = "' + MapLayerSourceInfo + '"onclick=" EditXmlDataEditor(this)">Edit</a>').appendTo(container);

If MapLayerSourceInfo has the value <source_info></source_info> I get the following, which is what I want.

<a href="javascript: void(0)" xml="<source_info></source_info>" onclick=" EditXmlDataEditor(this)">&lt;......&gt;</a>

If however MapLayerSourceInfo has the value <source_info />, jQuery appendTo gives me this:

<a href="javascript: void(0)" xml="<source_info></a>" onclick=" EditXmlDataEditor(this)">&lt;......&gt;</a>

It adds the closing tag for the anchor. How do I prevent this?

Upvotes: 0

Views: 112

Answers (3)

Ram
Ram

Reputation: 144699

You should either escape the string or use a different syntax for creating the element:

$('<a>', {
    xml: MapLayerSourceInfo,
    text: 'Edit',
    href: '#',
}).appendTo(container);

http://jsfiddle.net/mgm7egcq/

Using above syntax you force the jQuery to use the attr method behind the scene. As a suggestion, avoid using onclick attribute, it makes your code unmaintainable and generally is a bad practice. For dynamically generated elements you can delegate the events.

Upvotes: 2

ShaneQful
ShaneQful

Reputation: 2236

You have toe escape your characters within the html attributes, you can use somthing like underscores escape or write your own

http://underscorejs.org/#escape

So what you'll need to do is

$('<a href="javascript: void(0)" xml = "' + escape(MapLayerSourceInfo) + '"onclick=" EditXmlDataEditor(this)">Edit</a>').appendTo(container);

Where escape is something like:

function escapeHTML(s) { 
    return s.replace(/&/g, '&amp;')
        .replace(/"/g, '&quot;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;');
}

Basically any xml characters in the dom will be interpreted as such and the browser will try fix the dom because they are part of it so if you escape them you should be fine. Don't worry any js like $("selector for your link").attr("xml") will return the orginal xml.

Upvotes: 0

Afonso
Afonso

Reputation: 1

You could transform <source_info/> into <source_info></source_info>

    if (MapLayerSourceInfo == "<source_info/>"){
 MapLayerSourceInfo = "<source_info></source_info>"}

Upvotes: 0

Related Questions