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

Utilizing the `repeat` function within `grid-template-areas` eliminates the need to manually repeat grid cell

When working with grid-template-areas in CSS grid, I encountered a situation where I wanted a header to span the entire width. Instead of defining the template-grid-columns with repeat(12, 1fr), I was searching for a way to utilize repeat() so that I would ...

Modifying a single element within a class with Jquery

Is it possible to create a stack of pages on a website using JQuery? I found this image that shows what I'm trying to achieve: image. Instead of applying ID css for each page, I'd like to use JQuery. While researching similar questions, I came ac ...

What is the main purpose of using the CSS transform:translate() property?

When CSS3 introduced animations with transition properties, it gave developers two main ways to change the position of an element. The first method involves setting the element's position as absolute and adjusting the left, right, top, and bottom prop ...

Scan the HTML document for links and compare them with the elements in an array to see if

I'm facing a small issue that I need help solving. I have an array of keywords and I want to check if any href links on the page match those keywords. If they do, I need to apply some CSS effects to them. Currently, this is what I have: I implemented ...

Detecting when a directive element has not been clicked in Angular may involve checking for certain event behaviors

I am looking to enhance the functionality of the "deselect" feature in multiple directives like buttons and popovers. Specifically, I want my functions to activate when the user clicks on an element that is not part of the directive template. Currently, I ...

Display issues with React styled components preventing proper rendering on the screen

Having issues with my style components displaying in a web application I'm developing using React and Ruby on Rails. Everything was working fine until I added a third style component, now even after removing it, nothing shows up on the screen after ru ...

Issue with CSS in Internet Explorer 7

CSS CODE: .search { float: left; width: 100%; display: block; } .search ul.tabs { height: 23px; margin-top: 50px; padding: 0px; } /* FF ONLY */ .search ul.tabs, x:-moz-any-link { height: 26px; margin-top: 50px; padding: 0px; } .search ul.tabs ...

Setting the default date for multiple bootstrap datepickers is a convenient feature that can easily be implemented by

I am working with a dynamically generated table of inputs, where the first column is a date field. To implement the date selection functionality, I am utilizing the bootstrap-datepicker. Each input is functioning correctly as I have given them individual n ...

Changing the background color of required inputs that are empty using jQuery

I need help customizing the background color of required input fields that are left empty when a user submits a form. Some of the fields are optional, but I want only the required ones to be highlighted in red. Specifically, the required fields have been ...

Ways to create a downward expanding navigation menu when collapsed

Trying to accomplish the following, please refer to the image below. I am looking to have the yellow bar extend down when the collapsed menu is open. Currently, the navigation links are hidden behind the logo as shown in the second image below. Is there a ...

How can I retrieve XML through a URL using HTML5 and JavaScript?

Currently, I am looking to access an XML file through a URL link. My main goal is to retrieve the file automatically and extract its contents for further processing. However, I am facing difficulties in finding the appropriate method to obtain and read t ...

Issue encountered while incorporating a PHP file into Javascript code

I'm facing a particular issue where I have a PHP file that is supposed to provide me with a JSON object for display in my HTML file. Everything seems to be working fine as I am receiving an output that resembles a JSON object. Here's the PHP file ...

Using Vue.js to update the v-bind:style when the mouse hovers over the element

I am working with a span element that displays different background images based on certain conditions. Here is the HTML: <span v-if="type" :style="styles" > </span> In the computed properties section: ...

Having trouble adding a custom font with override to MuiCssBaseline in react-admin, the @global @font-face seems

I am attempting to integrate the NotoSansSC-Regular.otf font from Google into my react-admin application as the default font for simplified Chinese text. I have managed to make it work by including the fonts in the root HTML file using CSS, like this: ty ...

Managing JSON data retrieval and manipulation techniques

My code is set up to display the image, title, and summary for all entries in a JSON file. However, I only want to display the image, title, and summary for the first entry, and only show the title for the rest of the entries. Please advise. <html> ...

Tips for automatically resizing a canvas to fit the content within a scrollable container?

I have integrated PDF JS into my Vue3 project to overlay a <canvas id="draw_canvas"> on the rendered pdf document. This allows me to draw rectangles programmatically over the pdf, serving as markers for specific areas. The rendering proces ...

Looking for a way to identify when a DOM element is resized as a result of web fonts loading asynchronously?

Within this div element lies text styled with a custom font via CSS's @font-face attribute. The issue arises when the font hasn't loaded yet, causing a delay in updating the font style of the text within the div. As a result, taking measurements ...

Ensure the first column is fixed and all other columns have the same height

I have encountered an issue where the first column of my table has varying heights compared to the other columns, resulting in inconsistent row heights. Below is the code I am using: <div class="outer"> <div class="inner"> <table> ...

Is it possible for jquery JSON AJAX to block all users?

On my website, I use AJAX to load an RSS feed on the client side when the page loads. If a user repeatedly presses F5, could the owner of the RSS feed ban my entire website instead of just that one user? This would prevent others from loading the RSS feed ...

Utilizing AJAX to transmit data from an HTML page to a controller in Asp.net

Recently, I started using .net and encountered an issue where I'm attempting to transfer data from a .html file to the controller using AJAX. Here is my ajax call: var dataValue = { ID: 10, Name: 'Test' }; ...