October 28, 2024
Chicago 12, Melborne City, USA
javascript

Find out which children element is visible according to its class using a switch-statement in either jQuery or JS?


I’m trying to target the first children <p> element that is visible within its parent element and I can’t solve it on my own.

This is what I put together, but I have no knowledge on how to accomplish this.

This is the original HTML code without the <p> element:

<div class=".result-content">
   <div class="one">Text for one</div>
   <div class="two">Text for two</div>
   <div class="three">Text for three</div>
</div>

When I generate 1 of the 2 <p> elements on the fly, it looks like this:

<div class=".result-content">
   <p class="available">This is available</p>

   <div class="one">Text for one</div>
   <div class="two">Text for two</div>
   <div class="three">Text for three</div>
</div>

or it could be like this:

<div class=".result-content">
   <p class="not-available">This is NOT available</p>

   <div class="one">Text for one</div>
   <div class="two">Text for two</div>
   <div class="three">Text for three</div>
</div>

I’m using the switch statement because to me it looks organized than the if/if else/else statements.

var isVisible = ":visible";
var target = $('.result-content').children(":first");       
//var target;
switch (target.css('display') == isVisible) { 
    case $('.available'): 
        
        console.log('This is available!');
        break;
    case $('.not-available'): 
        console.log('This is NOT available!');
        break;
    default:
        //console.log('Nothing is available!!');
}

Thanks in advance!



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video