Guide on how to retrieve a clicked element

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!

Answer №2

Simply update your jQuery selection method:

View the Fiddle

$("#suggestionTags ul").on('click',function(){
    alert( $(this).find("li.nm").text() );
});

Answer №3

After extensive research, I have found the perfect solution for my query:

    $('ul').on('click', function() {
        alert($(this).find('li.name').text());
    });

I am puzzled as to why other alternatives did not work when integrated into my code, but on their own they perform flawlessly!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Prevent the Append button from being clicked when a duplicate entry is detected in jQuery

Hi there! I'm currently in the process of learning jQuery coding. Could anyone advise me on how to disable an entry or trigger an alert if it duplicates another APPENDED row? Below is the script I use for appending rows: var rowCount = 1; $('# ...

Issue with Jquery navigation toggle class not functioning properly following a link click

I am facing an issue with my navigation that consists of links with either the "active" or "inactive" class. I have written a jQuery script where, when a link is clicked, the last active one becomes inactive and the clicked one becomes active. However, the ...

Struggling to make @font-face function properly

I am attempting to incorporate a custom font into my website. In my CSS file, I have the following: body { font-family: HurmeGeometricSans4_SemiBold; } @font-face { font-family: HurmeGeometricSans4_SemiBold; src: url(resources/Hurme_Design_-_ ...

Keep track of the toggled state and prevent any flickering when the page is reloaded, all without the

After extensive searching, I couldn't find exactly what I needed. Therefore, I decided to utilize cookies to remember the toggled state of a div whether it's hidden or visible. However, I encountered an issue where there is flicker happening as t ...

Creating a Stylish CSS Table Utilizing DIV Elements: Preventing the Top Row from Scrolling

Utilizing a pure DIV table with the display: table, table-row, table-cell format for styling, I have managed to make the entire table scroll except for the header row. However, I am in search of methods that can prevent the header row (1st row) from scroll ...

Utilize jQuery and JSP (or PHP) to showcase detailed information about a specific item when a user clicks on it within an HTML page

For my upcoming college project, I am tasked with developing a movie library. The main page of the library will feature various movie posters. Upon clicking on a poster, users will be directed to a dedicated page displaying detailed information about the ...

Challenges related to height

Having an issue with height in my code. My footer is set up like this: <html> <body> <div class='wrap'> <div class=principal></div> <div class='clear'></div> <foo ...

Changing Image Size in Real Time

Trying to figure out the best way to handle this situation - I need to call a static image from an API server that requires height and width parameters for generating the image size. My website is CSS dynamic, adapting to different screen sizes including ...

Guide to customizing Highcharts for extracting targeted JSON information

I've been dedicating a significant amount of time trying to unravel this puzzle. Typically, I prefer researching solutions rather than posing questions, but this challenge has me completely perplexed. My goal is to generate a Highchart using data from ...

How can you adjust the dimensions of a child div?

Hey there! I've got a div called bat. #bat{ width:50%; height:50%; } Here's the HTML: <div id="bat">dynamic div will appear here</div> When dynamic content is placed inside the div and it's larger than #bat, th ...

Presentation Slider (HTML, CSS, JavaScript)

Embarking on my journey of creating webpages, I am eager to replicate the Windows 10 start UI and its browser animations. However, my lack of JavaScript knowledge presents a challenge. Any help in reviewing my code for potential issues would be greatly app ...

The iframe remains unresponsive and fails to resize as needed

I am facing an issue while trying to embed an iframe into one of my websites. It seems that the responsiveness is lost and it does not scale properly on mobile devices. You can see the issue here. Interestingly, when I place the same iframe on a plain HTM ...

On my website, two elements are stacked on top of each other

The CSS framework I am currently utilizing is Materialize Whenever I try to add a new element, it inexplicably appears below the ones above it. I did not specifically instruct it to be positioned underneath or below the cover container. Adding a z-index c ...

Tips for increasing a variable by one with each button click?

I have a simple JavaScript function called plusOne() that is designed to increment a variable by 1 each time a button is clicked, and then display the updated value on a webpage. However, I'm encountering an issue where the addition only occurs once. ...

The negative z-index is causing issues with my ability to select classes using jQuery

By setting a z-index of -3 for several divs in my background, I thought they wouldn't affect the formatting of elements in the foreground. But now I'm facing an issue where I can't click on those background divs when trying to target them wi ...

Ensure that the horizontal navigation items are equally spaced apart

I've managed to align my longer navigation bar items horizontally instead of vertically, but I'm struggling to evenly space them alongside the shorter items within the container. Despite trying various solutions found through research, I have not ...

Implementing a click event listener on an iframe that has been dynamically generated within another iframe

Below is the code I used to attach a click event to an iframe: $("#myframe").load(function() { $(this.contentWindow.document).on('click', function() { alert("It's working properly"); }); }) Everything seems to be working co ...

Ways to access data-style in a jQuery method

I need help implementing jQuery to toggle the display of certain divs on my webpage: HTML Elements: <div class="image" data-style="bw"><img src="img/bw1.jpg"></div> <div class="image" data-style="fauna"><img src="img/fauna1.jpg ...

Is there a way to shorten the length by left-clicking and increase it by right-clicking?

Illustration: section.my{margin: 20px;} <section class="my"></section> Hover over: section{padding: 10px;} Double click: section{border: 1px solid black;} ...

Guidelines for placing an HTML element in relation to another HTML element using CSS or JavaScript

Is there a way to position an HTML element in relation to another using CSS or JavaScript? I have attempted to copy the inner HTML of the "second-element" and append it inside the "first-element", but this approach is causing issues with other functional ...