<!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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With