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.
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.
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 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.
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.
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 =)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With