Hide all 'a' elements with text or innerHTML that matches the number '0' or a custom value using javascript or jQuery

人盡茶涼 提交于 2019-12-03 10:19:28

问题


I need to Hide all <a> elements with text or innerHTML that matches the number 'foo' or a custom value using javascript or jQuery.

<li><a href="#" class="dir">foo</a></li>

I have tried

jQuery(document).ready(function() {
    if (jquery().text().html("foo"){
        ('li >a').fadeOut()
    }
});

回答1:


$('a:contains(foo)').hide();

Done.

Or:

var customValue = "foo"
$('a').filter(function(){
    return this.innerHTML === customValue;
}).fadeOut();

With the later option you custom it a lot more, like:

var customValue = "foo"
$('a').filter(function(){
    return this.innerHTML === customValue &&
           $(this).closest('div').length;
}).fadeOut();



回答2:


One approach, assuming the text you're searching for is exactly the string you use, shamelessly stealing frompaying homage to Jonathan Sampson:

Creating the :exactly selector:

$.extend($.expr[":"], {
    exactly: function( element, index, details, collection ){
        return $(element).text() === details[3];
    }
});

Used like so:

$('a:exactly("foo")').fadeOut();

References:

  • Jonathan Sampson:
    • The blog entry for :exactly() selector: http://sampsonblog.com/279/creating-your-own-custom-jquery-filters
    • The Stack Overflow question that prompted the creation of :exactly(): Is there any selector to do a perfect match against text?


来源:https://stackoverflow.com/questions/10923102/hide-all-a-elements-with-text-or-innerhtml-that-matches-the-number-0-or-a-cu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!