JQuery How to continue Javascript for a new line?

This is a lingering question that I have, and although it may seem like a noob, this is normal, since I am alone.

How to continue a new line in jQuery selectors? I understand javascript newlines are just

(\) single backslash

For example,

 var someString = 'abc\ defghi'; alert(someString); 

However using jQuery - does this not work when I list long selectors? i.e.

 $('#id, .class, .class1, .class2, .class3, .class4, .class5, \ .class6, .class7').click(function() { //some stuff }); 

Can someone shed some light on how to solve this?

+8
source share
7 answers
 $('#id, .class, .class1, .class2, .class3, .class4, .class5, ' + '.class6, .class7').click(function() { //some stuff }); 

http://jsfiddle.net/X6QjK/

+16
source

That in between $() is just a string. Having said that, how would you split a string into two?

 $('big selection text' + 'more selection' + 'more selection still') 

Alternatively, you can add your collection after your initial selection:

 $('big selection text') .add('more selection') .add('more selection still') 
+3
source

jQuery has JavaScript. Do not be fooled into thinking that there is a difference. Does your code work with everything on one line?

I would suggest that your selector does not actually select any elements (DOM elements probably do not exist when the selector is called).

+2
source

In JavaScript, strings cannot span multiple lines, so to encode a multiline string, you should do the following:

 var s = "This is a\n" + "multiline\n" + "string.\n"; 

Note that newline characters ( \n ) are only required if you really need lines in a line. Your example would look like this:

 $('#id, .class, .class1, .class2, .class3, .class4, .class5, ' + '.class6, .class7').click(function() { //some stuff }); 
0
source

You can simply close the line and use the + operator to add lines.

 $('#id, .class, .class1, .class2, .class3, .class4, .class5,' + '.class6, .class7').click(function() { //some stuff }); 

That should work.

0
source

I suspect the reason this does not work for you is that when you feed a line on several lines like this, it obviously includes a new line character. Perhaps jQuery does not like this newline to be in its selector string.

My advice would be to simplify everything by providing each of the elements you want it to apply to one common class, which would negatively replace the need for excessively long selector strings like this.

But if you cannot do this, then you can solve the problem by breaking the line into separate sections and using + to combine them, rather than continuing the line above the line.

0
source

Today, another option uses template literals https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

 $('#id, .class, .class1, .class2, .class3, .class4, .class5, .class6, .class7').click(function() { //some stuff }); 
0
source

All Articles