我有一个带有值的范围要素列表:

    <span>Example1</span>
    <span>Example2</span>
    <span>Example3</span>
    <span>Example4</span>
    <span>Example5</span>


如何检查内部是否存在跨度,例如“ Example4”?

我尝试了以下操作,但没有结果:

    if($('span').textContent = value){
     console.log('exists');
    }

    if($('span').html(value){}
    if($('span').html(value).length > 0){}


但它们始终返回true。

谢谢阅读 :)

最佳答案

有一个:contains选择器:

if ( $('span:contains("Example4")').length > 0 ) { ... }


但是,如果有<span>个元素带有类似"Example 40"这样的文本,则采用这种方法will fail。为了进行严格的比较,您可以使用.filter方法的技巧:

if ( $('span').filter(function() {
    return $.trim($.text(this)) === 'Example4';
}).length > 0 ) { ... }

关于javascript - 是否存在具有特定innerHTML的元素?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23266540/

10-11 05:34