如何根据内容选择元素?

时间:2022-10-30 14:26:20

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

我需要能够选择具有特定内容的元素(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?

例如我有一些锚点,每个都有一个数字作为他们的文本。如何选择带有“1”的锚作为其文本?

I have tried this

我试过这个

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

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

这似乎适用于IE但不是ff或chrome!

3 个解决方案

#2


1  

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

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

EDIT =>这将仅使用1警告锚的文本,如果没有找到则将为null。

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

#3


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.

由于我正在搜索的锚点都在一个公共div中,我通过它缩小,然后运行客户过滤器函数找到确切的元素。

#1


#2


1  

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

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

EDIT =>这将仅使用1警告锚的文本,如果没有找到则将为null。

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

#3


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.

由于我正在搜索的锚点都在一个公共div中,我通过它缩小,然后运行客户过滤器函数找到确切的元素。