Reputation: 23
I am trying to get a specific li element within the closest/parent ul, however, I can't seem to get it working. It only works if the div is within the li element.
<ul>
<li>Test 1</li>
<li>Test 2</li>
<li>Test 3</li>
</ul>
<div>
<a id="a_test" href="#" onclick="Javascript:get_li(this);">Test</a>
</div>
function get_li(oElement) {
console.log("ul", $(oElement).parent("ul").find("li")[0]);
}
Upvotes: 1
Views: 1744
Reputation: 18987
Your code doesn't work because the div
is not under the ul
so the div
is not a child of ul
but both your ul
and div
are siblings. That means both these elements have same parent. So first find the parent of the div
and now find the ul
within this parent. Below is the sample
$(oElement).closest('div').parent().find("ul li")[0]
Upvotes: 0
Reputation: 15555
$('#a_test').click(function() {
var text = $(this).parent().prev('ul').find('li:nth-child(1)').text()
alert(text)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>Test 1</li>
<li>Test 2</li>
<li>Test 3</li>
</ul>
<div>
<a id="a_test" href="#">Test</a>
</div>
You need to get to parent of anchor by using .parent()
then get the ul using .prev()
then find the li element using .find()
Upvotes: 1