There is a selector in jQuery - :contains
Example:
str = 'test';
blocked_div = $(".mydiv:contains("+str+")");
blocked_div.find('img').hide();
...
<a href="http://example.com">test</a>
...
As I understand it's search for a "test" text inside a ".mydiv" element. But now i need to find a link "http://example.com" inside a ".mydiv" element, and :contains dont work in this situation. Can you recommend a solution to do this ?
Did you mean:
$(".mydiv a[href='example.com']");
You can also use *=
or ^=
filters to find links which contain specified text anywhere or at start of string respectively.
// find links containing "example" in href at any place
$(".mydiv a[href*='example']");
For your str
variable, you can modify it like:
$('.mydiv a[href=' + str + ']'); // exact match
$('.mydiv a[href*=' + str + ']'); // contains str anywhere in href
You want to test whether the string is contained in the HREF? This ought to do it:
$('.mydiv a[href~='+str+']');
The ~=
means the attribute on the left contains the string on the right.
Change the selector like following:
var str = 'test';
$(".mydiv a:contains("+str+")").attr('href'); // return `href` attribute of that `a`
// contains string test
To get the link with specific href
var str = 'http://example.com';
$(".mydiv a[href="'+ str+ '"]");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.