简体   繁体   中英

Select only (display:block) element from list of items Jquery

I'm making a menu and i need to select one particular element from a list of element returned by Jquery.

When i run on console :

 $("[type='subMenu']")

This returns 4 matching submenu elements.

<div type="subMenu" style="display:block">
<div type="subMenu" style="display:none">
<div type="subMenu" style="display:none">

Now, i need to select only the element having display:block

I tried

$("[type='subMenu']").css('display') == 'block'

but this give false as output.

and

$("[type='subMenu']").css('display')

this is giving output as none

Others have already pointed out the JQuery :visible selector. However, there are some performance issues with it, as pointed out in the JQuery API documentation :

Additional Notes:

  • Because :visible is a jQuery extension and not part of the CSS specification, queries using :visible cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :visible to select elements, first select the elements using a pure CSS selector, then use .filter(":visible") .
  • Using this selector heavily can have performance implications, as it may force the browser to re-render the page before it can determine visibility. Tracking the visibility of elements via other methods, using a class for example, can provide better performance.

If you'd prefer to avoid those issues, you could use a native CSS selector, instead. In plain ol' normal JavaScript, this would do the trick for you:

document.querySelector("[type=subMenu][style*=display\\:block]");

Or, if you need to select multiple elements at once:

document.querySelectorAll("[type=subMenu][style*=display\\:block]");

I believe the equivalent in JQuery (I don't use it) for both would be:

$("[type=subMenu][style*=display\\:block]");

If the only style that will ever be set inline on those tags is display then you can omit the * from the style attribute selector.

Try this:

console.log($("[type='subMenu']:visible")). 

It will give all visible elements

You can use filter or pseudo class.

$("[type='subMenu']").filter(function(){
    this.style.display == 'block';
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM