Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Jquery contains?

Tags:

jquery

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.

like image 697
chobo2 Avatar asked Sep 04 '09 23:09

chobo2


People also ask

Can I use contains selector?

The "contains" selector is useful in cases where we are looking for an element that "contains" some text (case sensitive). It is a good approach when we want to locate web elements that do not have a fixed index or id inside the web page.

What does $() mean in jQuery?

In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery. A (selector) to "query (or find)" HTML elements.

How do I find a word in a string using jQuery?

How to find if a word or a substring is present in the given string. In this case, we will use the includes() method which determines whether a string contains the specified word or a substring. If the word or substring is present in the given string, the includes() method returns true; otherwise, it returns false.

How do you check if a string contains another string in jQuery?

The simplest way to check to see if one string is a substring of another is to use . indexOf(substring) on the main string. This function returns an index of the location of the first occurrence, or –1 if the substring is not found.


1 Answers

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 =)

like image 63
Tomas Aschan Avatar answered Oct 01 '22 22:10

Tomas Aschan