A. Rossi A. Rossi - 6 months ago 17
jQuery Question

JQuery/Javascript select not visible element

I have a page with tabs, i would like select every span/input on each tabs, but not those in a hidden div.

There is a difference betwwen the hidden from tabs, and the hidden attribute ?.
For undertand this question, there is my code :

HTML

<input type="button" value="click me" id="btn">
<main>
<input id="tab1" class="tab" type="radio" name="tabs" checked>
<label for="tab1">Codepen</label>

<input id="tab2" class="tab" type="radio" name="tabs">
<label for="tab2">Dribbble</label>

<input id="tab3" class="tab" type="radio" name="tabs">
<label for="tab3">Dropbox</label>


<section id="content1">
<span id="span1">span1</span>
<input id="inp1" type="text" value="val" />
</section>

<section id="content2">
<span id="span2">span2</span>
<input id="inp2" type="text" value="val2" />
<div hidden>
<span id="span3">span3</span>
<input id="inp3" type="text" value="val3" />
</div>
</section>

<section id="content3">
<span id="span4">span4</span>
<input id="inp4" type="text" value="val4" />
<div>
<span id="span5">span5</span>
<input id="inp5" type="text" value="val5" />
</div>

<div hidden>
<div>
<span id="span6">span6</span>
<input id="inp6" type="text" value="val6" />
</div>
</div>
</section>
</main>


And my try in Jquery

$("#btn").click(function() {

$.each($("section").find("span, input"), function() {
if ($(this).is(":visible")) {
console.log($(this).attr("id"));
}

})
})


The output is :

span1
inp1


If i remove the if condition, output is :

span1
inp1
span2
inp2
span3
inp3
span4
inp4
span5
inp5
span6
inp6


And what i expect is :

span1
inp1
span2
inp2
span4
inp4
inp5
span5


And there is my JSFiddle for live demo

I don't know if this is clear, ask me in comment for more explication, and sorry for my english. Thanks

Answer

There are two solutions for this

$("#btn").click(function() {

console.log("Method 1");

$.each($("section").find("span, input"), function() {
  if ($(this).closest("[hidden]").length == 0)
   {
     console.log($(this).attr("id"));
   }

})

console.log("Method 2");

$.each($("section > span, section > input, section > div:not([hidden]) span, section > div:not([hidden]) input"), function() {
  if ($(this).closest("[hidden]").length == 0)
   {
     console.log($(this).attr("id"));
   }

})
})