有人能告诉我是否有可能根据其内容而不是通过ID或类来查找元素吗?

我试图找到没有不同的类或id的元素。(然后我需要找到该元素的父元素。)


当前回答

是的,使用jQuery包含选择器。

其他回答

可以使用:contains选择器根据元素的内容获取元素。

演示

(“div: contains美元(“测试”))。css (background-color’,‘红’); 这是一个测试 < div >另一个div < / div > <剧本剧本src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js " > < / >

在我看来是最好的办法。

$.fn.findByContentText = function (text) {
    return $(this).contents().filter(function () {
        return $(this).text().trim() == text.trim();
    });
};

在jQuery文档中,它说:

匹配的文本可以直接出现在所选元素中 该元素的任何子元素,或其组合

因此,仅仅使用:contains()选择器是不够的,你还需要检查你搜索的文本是否是你所目标元素的直接内容,类似这样:

function findElementByText(text) {
    var jSpot = $("b:contains(" + text + ")")
                .filter(function() { return $(this).children().length === 0;})
                .parent();  // because you asked the parent of that element

    return jSpot;
}

是的,使用jQuery包含选择器。

火箭的回答不管用。

<div>hhhhhh
<div>This is a test</div>
<div>Another Div</div>
</div>

我只是在这里修改了他的DEMO,您可以看到根DOM被选中了。

$('div:contains("test"):last').css('background-color', 'red');

在代码中添加“:last”选择器来修复这个问题。