I'm trying to set attribute value that contains a single quote:
var attr_value = "It's not working"; var html = "<label my_attr='" + attr_value + "'>Text</label>"; $('body').html(html);
However, I get the following result:
<label working="" not="" s="" my_attr="It">Text</label>
How could I fix this ?
Are double quotes allowed inside attribute values ?
Double quotes around attribute values are the most common in HTML, but single quotes can also be used.
No, there is not. The double quote ( " ) has special meaning inside a HTML attribute. If you want to put it into an attribute value, you must (this is not a true must but a good rule of thumb. It's a must if you use attributes delimited by double-quotes as you do in your question) write it as its entity " .
The HTML specification says: Attributes are placed inside the start tag, and consist of a name and a value, separated by an = character. The attribute value can remain unquoted if it doesn't contain spaces or any of " ' ` = < or > . Otherwise, it has to be quoted using either single or double quotes.
Yes, both quotes are allowed in attribute values, but you must HTML-escape the quote you're using as an attribute value delimiter, as well as other HTML-special characters like <
and &
:
function encodeHTML(s) { return s.split('&').join('&').split('<').join('<').split('"').join('"').split("'").join('''); } var html= '<label my_attr="'+encodeHTML(attr_value)+'">Text</label>';
However, you are usually much better off not trying to hack a document together from HTML strings. You risk bugs and HTML-injection (leading to cross-site-scripting security holes) every time you forget to escape. Instead, use DOM-style methods like attr()
, text()
and the construction shortcut:
$('body').append( $('<label>', {my_attr: attr_value, text: 'Text'}) );
You can use single quotes inside double quotes or double quotes inside single quotes. If you want to use single quotes inside single quotes or double quotes inside double quotes, you have to HTML encode them.
Valid markup:
<label attr="This 'works'!" /> <label attr='This "works" too' /> <label attr="This does NOT \"work\"" /> <label attr="And this is "OK", too" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With