palmtown palmtown - 6 months ago 39
HTML Question

Get outter parent UL using jquery

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]);

}

Answer

$('#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()

Comments