0

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 want 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'); 
1
  • some syntax errors in the example code (first part) Commented Dec 18, 2010 at 22:47

4 Answers 4

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot for your tips and insight on this, much appreciated!
1
$('a[title="' + currentElement + '"]').addClass('selectedThumb');

Comments

1

Try

$("a[title ='"+currentElement+"']").addClass('selectedThumb');

Notice the extra quotes.

1 Comment

Wow. Looks like I should refresh before posting.
0
$('[title='+currentElement+']').addClass('yourclass');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.