Question

I am new to jQuery and have created a little code snippet to check if any (i.e. one or more) of the following IDs is visible on a form.

The code works fine but I was wondering if I could achieve the same by checking for a class or name that I could assign to each ID so that it could also handle more IDs and I dont have to mention each of them separately.

Can someone here help me with this and tell me how to write it properly.

My Code (working):

if(($('#fail1').is(':visible')) || ($('#fail2').is(':visible')) || ($('#fail3').is(':visible')))
{
    // do something;
}
Was it helpful?

Solution

This is exactly the kind of behaviour a class is meant for - duplicating logic over a set of elements. It's possible to use an id attribute selector in jQuery although these are relatively slow and should be used as a last resort.

All you need to do is give the class to your elements and amend your code like this:

if ($('.fail').is(':visible')) {
    alert('at least one element is visible');
}

Example fiddle

OTHER TIPS

if($( "[id^='fail']" ).is(':visible') )
{
    // do something;
}

reference attribute-starts-with-selector

For the record, jQuery is not required to do that:

if (Array.prototype.some.call(document.querySelectorAll('.fail'), function (n) {
      return (window.getComputedStyle(n).display !== 'none');
    })) {
    console.log('at least one element is visible');
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top