tags:

views:

47

answers:

3

I need to be able to select an element that has certain content (innerHTML).

e.g. I have some anchors each with a number as their text. How can I select the anchor with '1' as its text?

I have tried this

$('a[innerHTML="1"]')

this seems to work in IE but not ff or chrome!

+1  A: 

selector contains

andres descalzo
+1  A: 

Try $("a:contains('1')")

EDIT => this will alert just the text of the anchor with 1 or null if nothing is found.

alert(FindLink($("a:contains('1')"), "1"));

function FindLink(element, textToFind) {
    var result = null;
    element.each(function() {
        if ($(this).text() === textToFind)
        {
            result = $(this).text();
            // you can change any attributes or css using $(this).css, etc
            // once the if statement is satisfied
        }
    });
    return result;
}
ryanulit
Link to doc is also in another answer, but here: http://docs.jquery.com/Selectors/contains#text
cjstehno
Thanks, but I need the text to be exact not just contains. e.g. if I have and anchor with 1 and 10 $("a:contains('1')") will return both. Can this be done with contains?
CeejeeB
I don't think you are going to be able to do this with contains. You may need to make a function where you pass in the value you are looking for and then loop through the results and explicity find the link that has the value. I'll edit my answer to do so.
ryanulit
Just filter it with `$("a:contains('1')").each(function(){...`
slebetman
A: 

Thanks for the replies. I have come up with a solution:

$('.pages a').filter(function() { return $(this).text() == 1; } )

Since the anchors I am searching are all in a common div I narrow down via that and then run a customer filter function the find the exact element.

CeejeeB
Nicely done. Glad you found an easier solution.
ryanulit