Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery 1.7 selector error

Tags:

jquery

ajax

this is my very first question.

I'm working on a fully Ajax system with jQuery, and it works fine with 1.6.2. When I tried to upgrade it to 1.7, this piece of code stopped working properly:

$("a[class!='']").live("click",function(e){
    e.preventDefault();
});

In 1.6.2, it prevents all hyperlink tags from working as a link if they have a class, but in 1.7 it stopped ALL links from working as real links, even those without classes.

Fiddle: http://jsfiddle.net/hBehg/

like image 828
rafael.js Avatar asked Nov 08 '11 16:11

rafael.js


2 Answers

Use $('a[class]'), this will select all elements which have the class attribute. As I said in my comment, checking for an empty value might not work if the element does not even have a class attribute.

Update: As pointed out by @Sidnicious, the documentation describes that this selector will also select those elements which do not have that attribute. If it didn't in 1.6, then it actually must have been a bug in that version, or they changed the description without mentioning it.

Of course, if you indeed have an empty class attribute, i.e. <a class="">, this will not work.

DEMO

Update 2: As @lonesomeday mentions in his comment, $('a[class][class!=""]') does work as you intended with $(a[class!=""]).

As others said, you can change to on in jQuery 1.7, which unifies the event handling methods, but it won't solve your particular problem.

like image 132
Felix Kling Avatar answered Oct 10 '22 23:10

Felix Kling


The jQuery docs describe the [name!=value] selector like this:

Select elements that either don't have the specified attribute, or do have the specified attribute but not with a certain value.

In your case, it will select every a which doesn’t have a class or whose class is not equal to an empty string. <a></a> and <a class=""></a> are not the same.

That might actually have been a bug in jQuery 1.6!

like image 43
s4y Avatar answered Oct 10 '22 22:10

s4y