Is there a better way to concatenate strings that have "'s (such as HTML tag attribute definitions) in jQuery than escaping the quote?
Escapy Example:
$(this).prepend("<label for=\""+$(this).attr("id")+"\">"+"a"+"</label>");
Is there a better way to concatenate strings that have "'s (such as HTML tag attribute definitions) in jQuery than escaping the quote?
Escapy Example:
$(this).prepend("<label for=\""+$(this).attr("id")+"\">"+"a"+"</label>");
you can use single quotes for the main string and then you don't have to escape the double quote.
$(this).prepend('<label for="'+$(this).attr("id")+'">'+ a +'</label>');
Single quotes?
$(this).prepend('<label for="'+$(this).attr("id")+'">'+'a'+'</label>');
or, jQuery:
$("<label>").attr("for", this.id).text(a).prependTo(this);
You can use the object method of creation ($(html, props)
), like this:
$('<label />', { for: this.id, text: 'a' }).prependTo(this);
//or:
$(this).prepend($('<label />', { for: this.id, text: 'a' }));
This has the advantage of calling .text()
internally, taking care of any encoding issues. Also, if you're doing this a lot, it'll be faster, since the HTML fragment is consistent and cached, so a clone of the node is used, rather than turning a string into a document fragment each time. The more elements like this you're creating, the faster it is over the string method. For the same caching reasons, the bigger the element (up to a 512 char string) the bigger the gains.
This is why I primarily use single quotes $('here')
. Less to worry about when you're working with HTML that inevitably is full of double quotes.
$('""""No worries!"""""""')
The Google JavaScript Style Guide agrees.
Single quotes are definitely the way to go. I recommend using them for all strings in javascript. Particularly when working with jQuery, it is much more common to need to use a double quote inside a string than a single quote, so it will save you a lot of time escaping and improve readability. Additionally, it'll save you keystrokes, no more pesky shift key :)