Jquery - select all anchor tags with display:block

2019-08-13 07:56发布

问题:

I can't get my head around how to do this?

Given a page full of anchor tags, I only want to select those elements with the CSS property display:block.

I think I can do it with a jQuery loop (warning pseudo code!)

var myarray;
$('a').each(function(arg1, arg2) { 
    if ($(arg2).css('display')=='block')
    myarray.push(arg2);
}

But isn't there a simpler way?

回答1:

You can use filter with a function as the parameter.

$('a').filter(function (index) {
                  return $(this).css("display") === "block";
              })


回答2:

Another way to do this would be to use jQuery's attribute selector:

$("a[style$='display: block;']")


回答3:

If you want to have it as a jquery tool (if you use it very often). You can extend the ":" selector by adding the following code to your project:

$.extend($.expr[':'], {
    "block": function(a, i, m) {
        return $(a).css("display") == "block";
    }
});

and then you can select all block anchors by saying this:

var res = $("a:block");

see example here: http://jsfiddle.net/zFatd/7/

[NOTE] as you can see in the example if you use ":block" on a naturally block element (i.e. div) it will still returns true. (in other words "div:block" is true unless you specifically give it something other than block)



回答4:

I would assume that the display property is set by having a certain class or other property. This should make the selection simpler by using that attribute. Also, if ther other anchors are hidden, you can display the visible ones using the $('a:visible') selector.



回答5:

Or more simple:

$("a:visible")


回答6:

//hide all items with css display as block (slow):

$('*').filter(function(index) {
  return $(this).css('display')=='block';
}).hide();