Home > Net >  How to get the id of previous ul
How to get the id of previous ul

Time:12-24

I have a div with 4 seperate lists, I need to know the id of the list before the one i click on.

So lets say i click on ul2 i need an alert of ul1 id.

currently im getting the clicked id with:

  var clicked_id = this.id;

and ive tried the following to get the above ul

  var div_id2 = $(this).parents(".divtest").next(".ultest").attr("id");
  var div_id = $(this).closest('ul').find('.ultest').attr('id');
  var x = $(this).prev().attr('id');

simplification of layout:

  <div id="doesnt matter" >
    <ul id="ul1" >
      <li id="doesnt matter"></li>
      <li></li>
      <li></li>
    </ul>
    <ul id="ul2" >
      <li></li>
      <li></li>
      <li></li>
    </ul>
    <ul id="ul3" >
      <li></li>
      <li></li>
      <li></li>
    </ul>
    <ul id="ul4" >
      <li></li>
      <li></li>
      <li></li>
    </ul>
  </div>

CodePudding user response:

Use jQuery.prev:

$('ul').click(function() {
  let prev = $(this).prev('ul')
  console.log(prev.attr('id'))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="doesnt matter" >
  <ul id="ul1" >
    <li id="doesnt matter">item</li>
    <li>item</li>
    <li>item</li>
  </ul>
  <ul id="ul2" >
    <li>item</li>
    <li>item</li>
    <li>item</li>
  </ul>
  <ul id="ul3" >
    <li>item</li>
    <li>item</li>
    <li>item</li>
  </ul>
  <ul id="ul4" >
    <li>item</li>
    <li>item</li>
    <li>item</li>
  </ul>
</div>

  • Related