How to select all anchor tags with specific text
Given a few anchor tags:
<a class="myclass" href="...">My Text</a> How to select bindings that match the class and with specific text. for example, select all bindings with the class: "myclass" and text: "My text"
$("a.myclass:contains('My Text')") You can create a custom selector similar to :contains for exact matches:
$.expr[':'].containsexactly = function(obj, index, meta, stack) { return $(obj).text() === meta[3]; }; var myAs = $("a.myclass:containsexactly('My Text')"); If your only concern is that the anchor text contains a specific line, go to @Dave Morton's solution. If, however, you want to exactly match a specific line, I would suggest something like this:
$.fn.textEquals = function(txt) { return $(this).text() == txt; } $(document).ready(function() { console.log($("a").textEquals("Hello")); console.log($("a").textEquals("Hefllo")) }); <a href="blah">Hello</a> A slightly improved version (with a second trimmer parameter):
$.fn.textEquals = function(txt,trim) { var text = (trim) ? $.trim($(this).text()) : $(this).text(); return text == txt; } $(document).ready(function() { console.log($("a.myclass").textEquals("Hello")); // true console.log($("a.anotherClass").textEquals("Foo", true)); // true console.log($("a.anotherClass").textEquals("Foo")); // false }); <a class="myclass" href="blah">Hello</a> <a class="anotherClass" href="blah"> Foo</a> First select all tags containing "MY text". Then, for each exact match, if it matches the condition, do what you want to do.
$(document).ready(function () { $("a:contains('My Text')").each(function () { $store = $(this).text(); if ($store == 'My Text') { //do Anything..... } }); }); If you donβt know the class of the desired object and just want to go after the link text, you can use
$(".myClass:contains('My Text')") If you donβt even know which element (e.g. a, p, link, ...), you can use
$(":contains('My Text')") (just leaving the part until : empty.)
I have to add here that it calls all the elements starting with <html> -Tag down to the desired element. The solution I could provide adds .last() to it, but this only works if there is only one element. Maybe sbda. knows the best solution here.
Actually, this should be an addition to the accepted answer, especially to the question @Amalgovinus.
I think this should work for an accurate match.
$("a.myclass").html() == "your text"