Determining the clicked node in a JavaScript environment

There are multiple spans with labels.

<span class="viewEdit">View and edit class one.</span>
<span class="viewEdit">View and edit class two.</span>
<span class="viewEdit">View and edit class three.</span>
<span class="viewEdit">View and edit class four.</span>
<span class="viewEdit">View and edit class five.</span>

I want to create a function that adds an 'on click' event to detect which span was clicked. For example, clicking the first span should return '0', the second '1'... and so on.

I am aware of using

document.getElementByClassName("viewEdit")

to create an array, but I'm unsure how to identify the clicked span.

I have attempted to find a solution for this question without success. If it has been answered elsewhere, I apologize for repeating it in a different way.

Answer №1

Your handler function will receive an event object.

function handleEvent(event) {
  var element = event.target;
  // Access the element here
}

event.target contains the node that was clicked on.

Answer №2

Check out the jsFiddle Demo here

Add a click handler to each element so that when clicked, it references the specific element triggering the event and makes an inference about its position relative to other elements.

Within the event handler, this will point to the element that triggered the event.

To achieve this, iterate through all elements with a specified class name:

var els = document.getElementsByClassName("viewEdit");
var elClicked = {};//Creating a public variable for potential use later
for( var i = 0; i < els.length; i++ ){

Then, within the loop, create an event handler and capture the index used to determine which number was clicked (this requires a closure).

for( var i = 0; i < els.length; i++ ){
 (function(local){
  els[i].onclick = function(){
   elClicked.element = this;
   elClicked.text = this.innerText;
   elClicked.index = local;
  };
 })(i)
}

Answer №3

By using this code snippet, you can easily determine the index of the clicked item within a specific collection.

var items = document.getElementsByClassName("viewEdit");

for (var i = 0; i < items.length; i++) {
    (function (index) {
        items[index].addEventListener("click", function () {
            for (var x = 0; x < items.length; x++) {
                if (items[x] === this) alert(x);
            }

        }, false);
    })(i);
}

This solution is straightforward and should fulfill your current requirement... Check out this fiddle for demonstration.

Answer №4

Simple method for accessing the parent node of span elements and adding an event handler...
See it in action!

const elements = document.querySelectorAll(".viewEdit");

elements[0].parentNode.addEventListener("click", function (event) {
    if (event.target.nodeName.toLowerCase() === "span") {
        alert([].indexOf.call(elements, event.target));
    }
}, false);

Answer №5

To capture all clicks, you can set up a click event listener on the document.body, then specify which elements to target based on their tag type and class name. Here's an example code snippet:

JavaScript

/*jslint maxerr: 50, indent: 4, browser: true */

(function () {
    "use strict";

    function addEvent(elem, event, fn) {
        if (typeof elem === "string") {
            elem = document.getElementById(elem);
        }

        function listenHandler(e) {
            var ret = fn.apply(null, arguments);

            if (ret === false) {
                e.stopPropagation();
                e.preventDefault();
            }

            return ret;
        }

        function attachHandler() {
            window.event.target = window.event.srcElement;

            var ret = fn.call(elem, window.event);

            if (ret === false) {
                window.event.returnValue = false;
                window.event.cancelBubble = true;
            }

            return ret;
        }

        if (elem.addEventListener) {
            elem.addEventListener(event, listenHandler, false);
        } else {
            elem.attachEvent("on" + event, attachHandler);
        }
    }

    function whatClicked(e) {
        var target = e.target;

        if (target.tagName.toUpperCase() === "SPAN" && /(^| )viewEdit( |$)/.test(target.className)) {
            console.log(target);
        }
    }

    addEvent(document.body, "click", whatClicked);
}());

Test this code on jsfiddle

Answer №6

<span class="viewEdit" onclick:"fn(this)">Click here to view and make changes to Class One.</span>
<span class="viewEdit" onclick:"fn(this)">Click here to view and make changes to Class Two.</span>
<span class="viewEdit" onclick:"fn(this)">Click here to view and make changes to Class Three.</span>
<span class="viewEdit" onclick:"fn(this)">Click here to view and make changes to Class Four.</span>
<span class="viewEdit" onclick:"fn(this)">Click here to view and make changes to Class Five.</span>

<script type="text/javascript">
   function fn(sender){
  //add the sender object to your array
  //or maybe even just the sender's id
}
</script>

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

What are some solutions for repairing unresponsive buttons on a webpage?

My task is to troubleshoot this webpage as the buttons are not functioning correctly. Here’s a snippet of the source code: <!DOCTYPE html> <html lang="en"> <head> ... </head> <body> <div id="container" ...

A guide on showing POST values from javascript XMLHttpRequest() in php

I have encountered an issue where I am using the XMLHttpRequest() javascript function to send parameters in Json format to another php page, but for some reason $_POST['appoverGUID'] is not receiving the posted values. Below is my Javascript cod ...

Accessing Facebook through Login with only a button visible

I need help with checking the user's login status on Facebook. I have implemented the code provided by Facebook, but all I see is the login button. How can I determine if the user is already logged in or not? function testAPI() { console.log(&apo ...

Add characters to div using JavaScript

I am curious about which framework, if any, would be most effective for capturing keystrokes and adding them to an HTML element such as a "p" element. My goal is to allow the client to type something on the keyboard and have it immediately displayed in the ...

What is the correct method for notifying the progress of time using jQuery?

I'm looking for a way to display the processing time of my PHP code using jQuery Here's an example of my PHP code : <?php //some queries to database ?> Below is my jQuery code: $.ajax({ type: "POST", url: "action. ...

Using jQuery to create a blinking effect on a specific letter in a string

I'm looking to create a text adventure using Canvas, and I want the parser to blink continuously, similar to the one in a Dos Console. The parser is stored as a global variable. How can I use jQuery to permanently change the character of this global v ...

What is the best way to assign a distinct index value to each object in an array

When I use the function below to add an index to each array object, all IDs end up with the same value when I check console.log: var foo = [...this.props.articleList]; foo.forEach(function(row, index) { row.id = index+1; }); console.log(foo); My des ...

When working with GWT, you can easily attach an event listener to any element on the host page

I am looking to implement a MouseOver event handler for any tag, specifically targeting anchor tags in a legacy HTML page. Following a GWT guide, I successfully utilized their JSNI method to retrieve all anchor tags with some minor adjustments for errors. ...

How can you exhibit various images without relying on the <img> tag?

Is there a more efficient way to display over 500 images from a folder on an HTML page without the need to manually write out each img src tag? I have searched online for solutions, but most suggestions involve using PHP or "glob", which I am hesitant to ...

Having trouble with my bootstrap slider carousel - it's just not cooperating

I incorporated Bootstrap's carousel to display the various courses on my website, featuring three courses at a time before transitioning to the next set of three. However, I am encountering an issue with this setup. Please see the image below for refe ...

Plot data points from geojson onto a leaflet map using markers

How can I efficiently import geoJson data (containing over 2000 coordinates) into a leaflet map? Below is a brief snippet of geo json: { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { ...

Converting function arguments into key/value pairs: A simple guide

I am looking for a way to achieve the following in NodeJS: a = 10 b = 20 c = 30 d = 40 ...... ...... function createObject(a, b, c, d, ....) => { // This function is expected to return an object. // return { a : 10, b : 20 ...

Is there a more efficient method than creating a separate variable for the navbar on each individual page where it is being utilized?

Apologies for the unclear title, I struggled to find the right wording and decided it would be easier to illustrate with code. Let's assume I have the following routes: router.get('/chest', (req, res)=>res.render('muscles/chest/chest ...

Unable to trigger AJAX POST with jQuery click handler

Important Note: Personally, I have a preference for utilizing jQuery over the shorthand $; although it involves more typing, I find it to be more readable. I am working on a simple form that allows users to input their first and last names as well as an e ...

Having trouble with a dropdown menu that allows for multi-select options?

var expanded = false; function showCheckboxes() { var checkboxes = document.getElementById("checkboxes"); if (!expanded) { checkboxes.style.display = "block"; expanded = true; } else { checkboxes.style.display = "none"; expanded = fa ...

The Camera component in React Native is not currently supporting foreground service

Trying to capture images in a foreground service, such as taking pictures while the user is using another app. Everything works fine within the app, but when the app is closed with the foreground service active, the camera stops working and shows this erro ...

Unable to perform a fetch request in IE9 after the page has finished loading

I'm currently encountering an issue with my Node and Express server setup. I have a separate API on a different server that needs to be accessed, but everything works fine except in IE9. The problem arises when I try to make a call to the API after lo ...

After the form is successfully submitted, you can remove the required attribute

Upon clicking the submit button of a form, an input box is highlighted with a red border if empty. After successful jQuery AJAX form submission, a message "data submitted" is displayed and the form is reset causing all input fields to be highlighted in red ...

The process of saving report filters and making them accessible for both running and scheduling tasks

I am facing a use case where I need to add query parameters to API calls and save them for future use. Essentially, I have a report that requires multiple filters to be saved - some predefined and others customizable. These saved filters can then be execut ...

Show dynamic HTML Dropdowns with nested JSON data

I've been racking my brains trying to implement this specific functionality in the UI using a combination of HTML5, Bootstrap, CSS, and JavaScript. My goal is to create dropdown menus in the UI by parsing JSON input data. Please Note: The keys withi ...