2

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!

3 Answers 3

1

selector contains

Sign up to request clarification or add additional context in comments.

Comments

1

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;
}

4 Comments

Link to doc is also in another answer, but here: docs.jquery.com/Selectors/contains#text
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?
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.
Just filter it with $("a:contains('1')").each(function(){...
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.