Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery label 'for' attribute selector

I am using Remy Sharp's labelover plugin for jQuery and I would like to exclude a label with the attribute for and value nature.

Here's an example of the code working:

$(document).ready(function() {
    $('form.default label').labelOver('over');
});

and what I'm trying to do:

$(document).ready(function() {
    $('form.default label').not($('label').attr('for','nature')).labelOver('over');
});

Can anyone see where I'm going wrong? Feels like I'm pretty close to what I need to do.

like image 372
Jimmy Joyce Avatar asked Aug 06 '11 14:08

Jimmy Joyce


People also ask

What is attribute selector jQuery?

jQuery [attribute|=value] Selector The [attribute|=value] selector selects each element with a specified attribute, with a value equal to a specified string (like "en") or starting with that string followed by a hyphen (like "en-us"). Tip: This selector is often used to handle language attributes.

How get data attribute value in jQuery?

To retrieve a data-* attribute value as an unconverted string, use the attr() method. Since jQuery 1.6, dashes in data-* attribute names have been processed in alignment with the HTML dataset API. $( "div" ).

How do you select an element by attribute?

The [attribute|="value"] selector is used to select elements with the specified attribute, whose value can be exactly the specified value, or the specified value followed by a hyphen (-). Note: The value has to be a whole word, either alone, like class="top", or followed by a hyphen( - ), like class="top-text".

How do I find the value of my ID?

You can simply use the jQuery attr() method to get or set the ID attribute value of an element.


2 Answers

attr is not a selector, it's a function that gets the attribute value with attribute name as the 1st argument, or sets it with a new value if one is passed as a 2ng argument.

Also, you excluded labels after selecting them with your not call, because the selector label matched all labels, and attr as I said did not filter that.

To select based on attribute, use this:

$(document).ready(function() {
    $("form.default label[for!='nature']").labelOver('over');
});

As you may have guessed, the [attribute='value'] is the selector for an attribute "equal" to some value, and [attribute!='value'] is the "not equal" version of it.

For reference see:
http://api.jquery.com/attribute-not-equal-selector/

For reference on all selectors:
http://api.jquery.com/category/selectors/

This is also referenced at my JavaScript & Web Dev Newsletter site.

like image 70
Meligy Avatar answered Oct 20 '22 08:10

Meligy


.attr('for', 'nature') is setting the value for the for attribute to nature

To filter by attributes, use [attribute="value"]:

$('form.default label').not('[for="nature"]').labelOver('over')
like image 2
mak Avatar answered Oct 20 '22 08:10

mak