开发者

Jquery - select all anchor tags with display:block

开发者 https://www.devze.com 2023-04-10 13:59 出处:网络
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 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?


You can use filter with a function as the parameter.

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


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

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


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)


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.


Or more simple:

$("a:visible")


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

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号