Retrieve the child element that is being clicked

Alright, I'm facing a little issue here (it seems simple, but I just can't seem to crack it)...

Let me paint the picture with a snippet of HTML code below:

<!-- New Website #1 -->
<!DOCTYPE html>
<html style='min-height:0px;'>
    <head>
        <title>Page Title</title>

        <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1">

        <link rel="stylesheet" href="jquery.mobile.min.css" />
        <link rel="stylesheet" href="custom.css" />
        <link rel="stylesheet" href="dev.css" />


    </head>

    <body id="jqm-website-6926" class=""  >


        <!-- New Page #1 -->
        <div data-role="page" comp-id="jqm-page-6271" id="jqm-page-6271" class="" data-add-back-btn="false" data-back-btn-text="" data-back-btn-theme="" data-dom-cache="false" data-theme="" data-title="" >

            <!-- New Header #1 -->
            <div data-role="header" comp-id="jqm-header-364" id="jqm-header-364" class="" data-position="" data-fullscreen="false" data-theme="" >
                <h1></h1>
            </div>
            <!-- / New Header #1 -->

            <!-- New Content #1 -->
            <div data-role="content" comp-id="jqm-content-3537" id="jqm-content-3537" class="" data-theme=""  >

                <!-- New Button #1 -->
                <div comp-id="jqm-button-1547" >
                    <a data-role="button" id="jqm-button-1547" class="" data-corners="true" data-icon="" data-iconpos="left" data-iconshadow="true" data-inline="false" data-mini="false" data-shadow="true" data-theme=""  href="#" data-transition="(null)">

                    </a>
                </div>
                <!-- / New Button #1 -->
            </div>
            <!-- / New Content #1 -->
        </div>
        <!-- / New Page #1 -->

        <!-- New Page #1 -->
        <div data-role="page" comp-id="jqm-page-9207" id="jqm-page-9207" class="" data-add-back-btn="false" data-back-btn-text="" data-back-btn-theme="" data-dom-cache="false" data-theme="" data-title="" >

        </div>
        <!-- / New Page #1 -->


        <script src="jquery.min.js"></script>
        <script src="jquery.mobile.min.js"></script>
        <script src="custom.js"></script>
        <script src="dev.js"></script>

    </body>
</html>
<!-- / New Website #1 -->

All I am looking to achieve is when clicking on a specific element with the comp-id attribute set, we should highlight (by adding the msp-selected class) that particular element only.

But alas, it's not working as expected...

Here's what I've attempted so far:

function removeAll()
{
    $("[comp-id]").each(function() {
        if ($(this)!==undefined) {
            $(this).removeClass("msp-selected");
        }
    });
}

$(document).ready( function() {
    $('[comp-id]:not(.msp-selected)').on('click', function(e) {
        removeAll();

        $(this).addClass('msp-selected');
    });
});

The caveat is:

  • When I click on the button (comp-id="jqm-button-1547")
  • It highlights : a) first the button, b) then jqm-content-3537, c) then jqm-page-6271
  • To put it simply, in the end, the 'page' gets highlighted instead of the button.

Any suggestions or ideas?


Also, here's a link to a fiddle for reference: http://jsfiddle.net/CTZD3/

Answer №1

One possible solution is to prevent the event from bubbling up to parent elements using event.stopPropagation();

$(document).ready( function() {
    $('[comp-id]:not(.msp-selected)').on('click', function(e) {
        removeAll();
        e.stopPropagation();
        $(this).addClass('msp-selected');
    });
});

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

Optimal approach for incorporating individual identifiers into a complex hierarchy of object arrays

I am looking to assign unique ids to an array of objects: For example: const exercises = [ { type: "yoga", locations: [ { name: 'studio', day: 'Wednesday' }, { name: 'home' ...

How can I prevent StateHasChanged() from affecting all open browsers in a Blazor Server-Side application?

Hey there, I'm new to Blazor but familiar with C#. This is my first time asking a question here so please bear with me. :) I am working on a Blazor server-side application where users can enter information and validate it based on server data. So far ...

Navigational issues while incorporating path.join with __dirname in node.js

Can you clarify the distinction between using path.join(__dirname, "src/js") and simply __dirname + "src/js") in a node.js environment? ...

SVG image element in Firefox does not respond to hover effect

I am currently working on developing an engaging SVG map. My goal is to have the image elements increase in size from 20px to 50px when hovered over. Below is an example of what I'm aiming to achieve: <svg xmlns="http://www.w3.org/2000/svg&quo ...

Having difficulty saving data in database using Ajax request from a Chrome extension

I am currently working on an extension that captures the page URL and saves it in a database once the user clicks the submit button. However, I have encountered a roadblock and believe there might be a missing piece in the extension setup that I cannot pi ...

Is there a way to navigate to the adjacent values in a json array?

I've been struggling with this issue for quite some time now. I have a list of items that can be moved to a div when clicked. My goal is to navigate through the items in the list (json) by clicking on Next and Previous buttons. As someone who is rela ...

An issue occurred while using AJAX in jQuery: there was an error converting a circular structure

After consoling JSON.stringify(stateArr), my JSON appears to be correct: { "shipping_options": [{ "id": "1", "name": "Kuala Lumpur", "rate": "222" }, { "id": "2", "name": "Labuan", "rate": "1" }] ...

Ways to retrieve information from JSON

I am currently trying to access the values of an object that is within an array which is inside another object. The data is structured as follows: [{ "id": "99a4e6ef-68b0-4cdc-8f2f-d0337290a9be", "stock_name": "J ...

Utilize the angularJS filter to emphasize the search text within the search results

I have a search box that filters results displayed on the screen. I am using a filter called 'startWith' for this purpose. Now, I need to implement a feature where the search text is highlighted among the search results in angularJS. For example ...

"Vue.js: The Ultimate Guide to Event Management and Data Handling

I recently started learning Vue.js and I'm having some difficulty with my coding exercises: The task is to have a menu button that opens a dropdown box when clicked, and when any selection is made, it should go back to the menu button. index.js cons ...

Ways to combine multiple tags in HTML using jQuery

I'm new to jQuery and I want to add multiple tags to my HTML but I'm not sure how to do it. Here's the jQuery code I wrote but I keep getting an error: var message = "hello"; var additionalMessage = '<li class="message-entry"& ...

jQuery Table Sorting - Reorder Automatically Upon Page Initialization

I stumbled upon this amazing JS Fiddle. How can I tweak it to sort the third column in descending order when the page loads? $(document).on('click', 'th', function() { var table = $(this).parents('table').eq(0); var rows ...

Using Swig's conditional extend tag with Express.js and Node.js to leverage dynamic content rendering

Is there a way to make the extend tag for the Swig templating engine conditional or able to use a passed variable? Instead of using this code: {% extends '../layouts/layout.view' %} I would prefer to do something like this: {% extends layout ...

Manipulating JSON objects within a map using jQuery and Gson

I am working with a Java object that contains several nested object fields with basic fields in them. Here is an example: Template { String name; EmailMessage defaultEmailMessage; } EmailMessage { String emailSubject; String emailBody; } ...

How can I successfully add an element to a nested array without making any mistakes in saving it?

Hello everyone, I'm new here. I previously posted about a similar issue, but now I have a different one. I am encountering this object: singleChat = [ { "chatid": 10000414, "connected": true, "index": 0, ...

What are the issues with the latest API routing in Next.js?

I am encountering an error that says: SyntaxError: Unexpected token s in JSON at position 0 Here is my code: import { PrismaClient } from '@prisma/client'; import { IDPay } from 'idpay'; import { NextResponse } from 'next/server&ap ...

The counter variable does not function properly within a setInterval function

I have encountered an issue with my scroll-counter variable inside the setInterval function. It increments by 1 each time the setInterval function runs, which is supposed to happen 20 times before stopping. However, I noticed that the value of this variabl ...

Can Angular 4 experience race conditions?

Here is a snippet of my Angular 4 Service code: @Injectable() export class MyService { private myArray: string[] = []; constructor() { } private calculate(result): void { myArray.length = 0; // Perform calculations and add results to myAr ...

Ruby on Rails and JSON: Increment a counter with a button press

How can I update a count on my view without refreshing the page when a button is clicked? application.js $(document).on('ajax:success', '.follow-btn-show', function(e){ let data = e.detail[0]; let $el = $(this); let method = this ...

Reposition the selection column to the right side within the UI-Grid

I am currently working with ui-grid and I need help relocating the selection column to the right side. Appreciate any assistance. Thank you! ...