tags:

views:

1516

answers:

2

Hi

I am looking at the jquery site at the contains selector.

$("div:contains('John')").css("text-decoration", "underline");

How can I make this so it takes a non hard-coded value in? I tried to do something like this

$("div:contains(" + name + ")")

but that does not seem to work and is very messy. I am probably just missing some brace or something but is there a clean way that will work? Since even if I get this to work the next time I have to expand it will be the same problem again with have so many concatenations and stuff.

+2  A: 

try it $("div:contains('" + name + "')")

john
+5  A: 

You're missing the quotes around the parameter.

$('div:contains("' + name + '")').css( ... );

I try to always use single quotes for string delimiters, and double quotes for actual quotes in strings when writing JS. Either way works, but being consistent helps reading the strings =)

Tomas Lycken
Personally I prefer it the other way around, but consistency is key. +1
TreeUK
Yes - either way works, and consistency is the key. I prefer single quotes as string delimiters mostly because I think it makes the code look "cleaner" - for each string there's two dots less on my screen... ;) On the other hand, if you want consistency with other languages (C#, for example) you probably want to use double quotes.
Tomas Lycken
I like using single quotes in javascript myself since then you don't have to escape html attributes. I must admit sometimes I use double quotes(if I see it I correct it) since it a must in C# and most other languages. Ya that's what I thought I forgot something. NO beter way to right it? they should add like String.Format from C# to jquery that would make things nicer.
chobo2