Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Select Href By Text

I have the following html:

<a href="#DDD">Link here </a>

And want to be able to select it by saying get the A tag which has the text "Link Here"

I have tried:

    $('a[value="Link here"]')
    $('a :contains("Link here")')

But this doesn't work.

Cant seem to see where I am going wrong.

like image 727
Lemex Avatar asked Nov 28 '13 11:11

Lemex


2 Answers

There shouldn't be a space between the tagname and the pseudo selector. A space denotes :contains("Link here") is another element, inside a, not the same one. You should be using:

$('a:contains("Link here")')

JSFiddle

:contains will select an element even if has more than that in the parameters (i.e: 'Link here bla bla bla' would be returned). If you need the text inside to be precisely 'Link here ', you can use filter():

$('a').filter(function(){
    return this.innerHTML == 'Link here '; // (Did you know you have a space at the end?)
}).css({background:"#F00"});

JSFiddle

like image 110
George Avatar answered Sep 27 '22 17:09

George


$("a.myclass:contains('Text')")

this ll work :D

like image 20
Žarko Selak Avatar answered Sep 27 '22 15:09

Žarko Selak