Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax error, unrecognized expression: , $(selector).before(",");

I've been using this one line of code for a couple of years now with jQuery 1.2.6.

$("#acListTemp div.amenitiesDiv label").before(",");

I just upgraded to jQuery 1.6.1 and now it is giving me this error:

Syntax error, unrecognized expression: ,

I also tried this, but it yielded the same error:

theChar = ",";
$("#acListTemp div.amenitiesDiv label").before(theChar);

I checked the jQuery API page for the before command, but I'm still stumped. Any help is greatly appreciated!

like image 653
Dan Avatar asked Jun 09 '11 15:06

Dan


1 Answers

If you're using .insertBefore() instead of .before(), you'll get that error.

The error doesn't appear using insertBefore() in jQuery 1.2.6


Looks like the error comes specifically from Sizzle:

https://github.com/jquery/sizzle/blob/master/sizzle.js#L325-327

Sizzle.error = function( msg ) {
    throw "Syntax error, unrecognized expression: " + msg;
};

...so I'd guess that somewhere in your code you're using "," as a selector, perhaps in insertBefore() or some other method that expects a selector.


EDIT:

From the comments below, it has been determined that jQuery does not fail silently as expected when calling .before() against a jQuery object for which no matches are found for its selector.

Seems like a bug to me, but I'm sure the jQuery guys will come up with some reason why this is the desired behavior.

You can see the issue here: https://github.com/jquery/jquery/blob/1.6.1/src/manipulation.js#L130-140

before: function() {
    if ( this[0] && this[0].parentNode ) {
        return this.domManip(arguments, false, function( elem ) {
            this.parentNode.insertBefore( elem, this );
        });
    } else if ( arguments.length ) {
        var set = jQuery(arguments[0]);
        set.push.apply( set, this.toArray() );
        return this.pushStack( set, "before", arguments );
    }
},

As you can see, there are only 2 tests.

  • The first checks to see if there is at least one element in the jQuery object (and if it has a parentNode). If so, it inserts the content before the matched elements.

  • If there were no elements, it just checks to see if any arguments were passed, and if so, it seems to assume that the first one is a selector (or perhaps a tag), and it goes ahead and sends that to the jQuery function.

var set = jQuery(arguments[0]);

So if you're trying to insert a ",", but your selector didn't find any matches, jQuery will end up doing:

var set = jQuery(",");

...which is an invalid expression for Sizzle to process.

like image 90
user113716 Avatar answered Sep 28 '22 06:09

user113716