Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get span id with jquery when i click the element mathematics/physics/checmistry

<!DOCTYPE html>
<html>

<head>
    <title>jQuery Accordion Menu Demo</title>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script src="main.js" type="text/javascript"></script>
</head>

<body>
    <div id='menu'>
        <ul>
            <li> <a href='#'><span id="Science">Science</span></a>
                <ul>
                    <li><a href='#'>Mathematics</a></li>
                    <li><a href='#'>Physics</a></li>
                    <li><a href='#'>Chemistry</a></li>
                </ul>
            </li>
        </ul>
    </div>
    <script>
        $('#menu li>ul>li').click(function() {
            alert(span id is Science);
        });
    </script>
</body>

</html>

Here is the code what I am trying to do.

I want that when a user clicks on the Mathematics or Physics or Chemistry, it should show in ALERT using JQuery the parent's SPAN ID.

like image 296
Riswan Abi Avatar asked Oct 30 '22 10:10

Riswan Abi


1 Answers

You can use relationship

$('#menu li>ul>li').click(function() {
    var id = $(this)
        .parent() //Travese up to UL
        .closest('li') //Travese up to li
        .find('span') //Finds the span
        .attr('id'); //Fetches the id attribute

    alert('span id is: ' + id);
});

$(function() {
  $('#menu li>ul>li').click(function() {
    var id = $(this)
      .parent() //Travese up to UL
      .closest('li') //Travese up to li
      .find('span') //Finds the span
      .attr('id'); //Fetches the id attribute

    alert('span id is: ' + id);
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='menu'>
  <ul>
    <li> <a href='#'><span id="Science">Science</span></a>
      <ul>
        <li><a href='#'>Mathematics</a>
        </li>
        <li><a href='#'>Physics</a>
        </li>
        <li><a href='#'>Chemistry</a>
        </li>
      </ul>
    </li>
  </ul>
</div>
like image 87
Satpal Avatar answered Nov 11 '22 04:11

Satpal