jQuery addClass to element based on attribute value
I am stuck with this and need some help. I know the logical solution for this, but not sure how to translate it to jQuery code (newbie here :)). Any suggestions or help greatly appreciated!
I need to add a css class (active class), to an element that has a title attribute equal to the value of a variable. So, let's say my variable currentElement = 'great day'. There is also an a tag element on the page that has the title attribute of 'great day', such as <a title='great day' href='#'>
.
With jQuery I wan开发者_运维问答t to: Find a tag in the DOM where currentElement == a tag title and add css class. So, ideally it should find that a tag and add the css class to it.
I came up with something like this but not working:
/* set currentElement var to the src attribute
value of an a tag on the page
this works */
var currentElement = $('#greatLink'] img[src*=' + test + ']').attr('src');
/* now find an a tag on the page that has
the same title attribute as var currentElement
this does not work */
$("a[title ='+currentElement+']").addClass('selectedThumb');
I think you just need to change your selector to use double quotes instead of the nested single quotes that you have:
$( 'a[ title=' + currentElement + ']' ).addClass( 'selectedThumb' );
Just to point out, the value of the attribute in the selector doesn't need to be quoted. e.g.
$( 'a[ title="foo" ]' )
is the same as
$( 'a[ title=foo ]' )
The entire selector itself is just a string. Whether or not you quote the value foo in the sample above is irrelevant to the result. While it might look more "correct" to quote the value, since it's not necessary I find it easier to just leave it off. It almost certainly makes it less confusing in the issue such as yours, where you're concatenating literal strings with variable values.
$('a[title="' + currentElement + '"]').addClass('selectedThumb');
Try
$("a[title ='"+currentElement+"']").addClass('selectedThumb');
Notice the extra quotes.
$('[title='+currentElement+']').addClass('yourclass');
精彩评论