Reputation: 25
I'm trying to find the first "visible" li
, in the code below this would be li2-2
.
But for some reason .children('li:visible')
or .attr()
gives me the first <li>
from <ul>
.
How do I fix this?
alert($("#myul").children('li:visible').attr("id"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body class="descendants">body (great-grandparent)
<div style="width:500px;">div (grandparent)
<ul id="myul">ul (direct parent)
<li style="visibility:hidden;" id="li1-1">li (child)
<span>span (grandchild)</span>
</li>
<li style="visibility:visible;" id="li2-2">li (child)
<span>span (grandchild)</span>
</li>
<li style="visibility:hidden;" id="li3-3">li (child)
<span>span (grandchild)</span>
</li>
<li style="visibility:visible;" id="li4-4">li (child)
<span>span (grandchild)</span>
</li>
</ul>
</div>
</body>
Upvotes: 1
Views: 44
Reputation: 109
You can use it in following way:
alert($("#myul").children('li[style="visibility:visible;"]').attr("id"));
Upvotes: 1
Reputation: 823
You can select the specific child using nth-child
selector
$(document).ready(function(){
alert($("#myul li:nth-child(2):visible").attr("id"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="width:500px;">div (grandparent)
<ul id="myul">ul (direct parent)
<li style="visibility:hidden;" id="li1-1">li (child)
<span>span (grandchild)</span>
</li>
<li style="visibility:visible;" id="li2-2">li (child)
<span>span (grandchild)</span>
</li>
<li style="visibility:hidden;" id="li3-3">li (child)
<span>span (grandchild)</span>
</li>
<li style="visibility:visible;" id="li4-4">li (child)
<span>span (grandchild)</span>
</li>
</ul>
</div>
Upvotes: 1
Reputation: 21489
As mentioned in jquery doc elements with visibility: hidden or opacity: 0 are considered visible.
That cause your code select all li
s.
You can use .filter()
to filtering element has visibility:visible
var id = $("#myul").children('li').filter(function(){
return $(this).css("visibility") == "visible"
}).first().attr("id");
console.log(id);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="width:500px;">div (grandparent)
<ul id="myul">ul (direct parent)
<li style="visibility:hidden;" id="li1-1">li (child)
<span>span (grandchild)</span>
</li>
<li style="visibility:visible;" id="li2-2">li (child)
<span>span (grandchild)</span>
</li>
<li style="visibility:hidden;" id="li3-3">li (child)
<span>span (grandchild)</span>
</li>
<li style="visibility:visible;" id="li4-4">li (child)
<span>span (grandchild)</span>
</li>
</ul>
</div>
Upvotes: 2