user2571510
user2571510

Reputation: 11377

Check for class or name instead of ID (simple code)

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;
}

Upvotes: 1

Views: 109

Answers (3)

Noe
Noe

Reputation: 386

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');
}

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

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

Upvotes: 3

Rituraj ratan
Rituraj ratan

Reputation: 10378

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

reference attribute-starts-with-selector

Upvotes: 2

Related Questions