When I click on the <ul>
inside this div
, I want to retrieve the id="nm"
.
<div id="suggestionTags">
<ul>
<li class="nm">Commonwealth</li>
<span class="cty"> x GB</span>
<li class="hse">Commonwealth</li>
<li class="yrs">1649-1653</li>
</ul>
<ul>
<li class="nm">Oliver Cromwell</li>
<span class="cty"> x GB</span>
<li class="hse">Commonwealth</li>
<li class="yrs">1653-1658</li>
</ul>
<ul>
<li class="nm">Richard Cromwell</li>
<span class="cty"> x GB</span>
<li class="hse">Commonwealth</li>
<li class="yrs">1658-1659</li>
</ul>
<ul>
<li class="nm">Elizabeth II ((Head of the Commonwealth of Nations))</li>
<span class="cty"> x GB</span>
<li class="hse">House of Windsor</li>
<li class="yrs">1952-</li>
</ul>
</div>
Here is a snippet of the JavaScript code:
$("#suggestionTags").on('click',function(){
alert( $(this).find("li.nm").text() );
});
However, this code retrieves everything instead of just the id="nm"
of the clicked element. Can someone help me with this?
EDIT:
The proposed solutions work well in http://jsfiddle.net/. However, I am still facing a problem with my own code.
<script language="JavaScript">
$(document).ready(function()
{
//this is the code that does'nt work
$('#suggestionTags ul').on('click', function() {
alert($(this).find("li.nm").text());
});
//end of part
var o = [];
$('#scrivo').keyup(function()
{
if ($('#scrivo').val() <= 0) {
$('#suggestionTags').empty();
return;
}
var json = (function() {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "re.json",
'dataType': "json",
'success': function(data) {
json = data;
}
});
return json.Re;
})();
o = $.grep(json, function(n) {
return n.nm.indexOf($('#scrivo').val()) !== -1;
}, false);
$('#suggestionTags').empty();
var html = "";
$.each(o, function(index, value) {
html += '<ul>';
$.each(value, function(i, v) {
switch (i) {
case "nm":
html += "<li class='nm'>" + v + "</li>";
break;
case "cty":
html += "<span class='cty'> x " + v + "</span>";
break;
case "hse":
html += "<li class='hse'>" + v + "</li>";
break;
case "yrs":
html += "<li class='yrs'>" + v + "</li>";
break;
}
;
...
This is an overview of my code and the JSON file it interacts with. The issue arises when trying to retrieve only a specific part of the HTML upon clicking, and so far I haven't been able to achieve what I intended. Suggestions or insights are appreciated!