Adam
Adam

Reputation: 1971

jQuery if visible

 <div id="chatCenterMembers">
   <div class="chatmember">
       <a title="Blah Blah Blah">
          <div class="newchatmessage" style="display: block;"></div>

How can I capture the visible div in an if statement?

I have $(this) set to <div class="chatmember"> - second line from the top.

I've been working with below but had now luck so far.

if($(this+' a div.newchatmessage').filter(":visible")) {

Above just drops out...

I've also tried below and it doesn't work either

if ($(this + 'a div.newchatmessage').is(':visible')) {

Upvotes: 14

Views: 47886

Answers (3)

Ken Johnson
Ken Johnson

Reputation: 330

I ran into a similar situation and wanted to note that you should be wary of the jquery selector returning more than one element. I believe the .is(':visible') check will only evaluate the first element in the array. You can check to see if all elements returned by that selector are visible with something like this.

if($('.someElementWithThisClass:visible').length > 0){
    //Do it to it
}

Upvotes: 0

Joakim Johansson
Joakim Johansson

Reputation: 3194

Use .is() to check if an element fills a certain requirement, like such:

if ($(this).find('a div.newchatmessage').is(':visible'))

Or, if you want it more readable:

var element = $(this).find('a div.newchatmessage');

if (element.is(':visible')) {
    // Do your thing
}

Upvotes: 49

user57508
user57508

Reputation:

.is()

for any detailed information on this method, just scroll down a bit ... there's a bunch of examples!

edit (thanks for the hint @Wesley Murch): if this does not work, your selector might be wrong ... $(this+' a div.newchatmessage') looks quite strange ... it might rather be $('a div.newchatmessage', this) or $('a div.newchatmessage', $(this)) depending on this being a jQuery-variable or not

Upvotes: 11

Related Questions