开发者

I want to select an item from an unordered list

开发者 https://www.devze.com 2023-04-10 03:16 出处:网络
I need to add a class to the list item that matches document.title. My understanding is that I need to do something along the lines of

I need to add a class to the list item that matches document.title.

My understanding is that I need to do something along the lines of

$('.mylist li:contains(thetitle)').addClass('blah')

but c开发者_开发百科ontains seems to take a string rather than a variable. I am sure this is obvious, but I have wasted a stupid amount of time on it already. Thanks in advance.


Just add the document.title to using standard string concatenation:

$('.mylist li:contains(' + document.title + ')').addClass('blah');


You mean like this $('.mylist li:contains(' + document.title + ')').addClass('blah')?


You'll have to quote the variable, since contains requires a string as a parameter. Additionally, if the document.title can contain quotes itself, you'll have to escape them.

var escaped = document.title.replace('\'', '\\\'');
$('.mylist li:contains(\'' + escaped + '\')').addClass('blah');
0

精彩评论

暂无评论...
验证码 换一张
取 消