What is the method to obtain the selector string for an HTML node element?

Essentially, my goal is to extract the selector string from an HTML element. Specifically, I want to start with the HTML element and retrieve its selector string (for example: button#myButton)

function onclicked(e){
 console.log(e.target);  // This returns the node HTML element
}

https://i.sstatic.net/Q4WLT.png

If I am unaware of the id or element beforehand, and only discover it upon clicking.

I am looking to obtain the selector string from e.target that matches the screenshot.

How can I achieve this?

function onclicked(e){
  console.log(e.target);
}
<div>
  <div>
    <div>
      <div>
        <button id="myButton" onclick="onclicked(event)">click</button>
      </div>
    </div>
  </div>
</div>

Answer №1

Let me be completely open with you, I must admit that I'm a bit unsure about the intention behind your approach here. Since you are already utilizing document.querySelector, why not just store the button directly? Is there any specific reason for choosing to store the query selector string instead of the actual DOM element?

I've sort of outlined a pseudo code implementation that I believe addresses your query. However, I have to confess that I might not fully grasp the objective behind your actions or the rationale for doing it this particular way.

I suggest taking a look at the proposed solution and giving it a review. It may not be the most elegant solution, but rather a straightforward attempt to tackle the issue at hand. Feel free to share any feedback in case this response does not align with what you were aiming for. I'm here to assist in any way I can! 🙂

const log = console.log;

const cache = {
  element: undefined,
  selector: undefined
};

function onClicked(event) {
  log(event.target);
  const element = event.target;
  cache.element = element;
  cache.selector = element.tagName.toLowerCase() + '#' + element.getAttribute('id');
  log(cache);
}
<div>
  <div>
    <div>
      <div>
        <button onclick="onClicked(event)" id="myButton">click</button>
      </div>
    </div>
  </div>
</div>

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

Trouble with uploading images through multer is causing issues

When setting up multer, I followed this configuration let multer = require('multer'); let apiRoutes = express.Router(); let UPLOAD_PATH = '../uploads'; let storage = multer.diskStorage({ destination: (req, file, cb) => { ...

Use an array to store nested JSON fields

I'm currently seeking to enhance my proficiency in utilizing JavasScript, React, and Material-UI. I am faced with the challenge of sorting my table using a nested JSON structure and I am encountering difficulties with assigning the JSON fields to my a ...

Steps to set up gapi-script authentication with next-auth in a Next.js application

I have encountered an issue while working on my open-source project that involves utilizing the Google Drive API. Can anyone guide me on how to set up gapi-script authentication using next-auth in a Next.js project? I have managed to implement authentica ...

jquery mobile listview extension not functioning as expected

My JQM menu is displayed as a listview, and I want it to be normal on every page except one where it should have 2 extra items. Despite searching online for solutions, nothing seems to work. Here are some of the things I've attempted: -location.reloa ...

Use Q.js's Q.all() method when dealing with an array of promises of unknown length

I am looking to retrieve an array of promises using Q.all(); such as the code snippet below: return Q.all([ list[0].getCssValue('height'), list[1].getCssValue('height'), ..., lis ...

Unique ActionBar design for my NativeScript-Vue application

I'm currently working on customizing the ActionBar for my nativescript-vue app. I have implemented FlexBoxLayout within the ActionBar, but I am facing an issue where the icon and title of the bar are not aligning to the left as intended; instead, they ...

Eliminate forward slashes from the telephone number

I am trying to figure out how to format a USA phone number by removing slashes and brackets. I have searched on Google, but I cannot find the answer. I would like to use regex to achieve this, while keeping the plus sign at the start intact. For example, ...

Implementing asynchronous file reading with module.exports in Node.js

Apologies in advance for what may seem like a basic question, but I'm delving into the inner workings of node and need help with a particular issue: I am trying to send an object or file from fs.readFile using require and module.exports. So far, this ...

Automatically close Bootstrap 4 modal popups

I am using Bootstrap 4 and trying to make my modal automatically close after 3 seconds. I attempted a solution but it seems to not be functioning correctly. The modal itself works fine, but the auto-closing feature is not working as expected. Below is the ...

JavaScript callbacks using customized parameters

I am currently grappling with the challenge of incorporating an asynchronous callback in node without prior knowledge of the potential arguments. To provide more clarity, let me outline the synchronous version of my objective. function isAuthorized(userI ...

The replace() function is failing to replace the provided inputs

Supposedly, when a user types in certain profanity and submits it, the word is supposed to be replaced with a censored version. Unfortunately, this feature is not working as expected. The word appears uncensored. Do you think implementing if/else stateme ...

Why is the image cut in half on mobile devices but displaying correctly on computer screens? Could it be an issue with

There seems to be an issue on mobile screens that does not occur on computer screens. When the user clicks on the image, it disappears, and when they click another button, it reappears. However, there is a problem with how the image appears - it is cut off ...

Using Async functions with Node.js Express.js router

I've been trying to search on Google, but I can't seem to find a clear answer to this one... Is it possible to pass ES7 async functions to the Express router? For example: var express = require('express'); var app = express(); app.ge ...

How to stop Mouseenter event from bubbling up in an unordered list of hyperlinks using Vue 3

I've experimented with various methods to prevent event bubbling on the mouseenter event, but I'm still encountering an issue. When I hover over a link, the event is triggered for all the links as if they were all being hovered over simultaneousl ...

Obtaining the source code from a different domain website with the help of jQuery

Is there a way to extract part of the source code from a YouTube page without using server-side programming? I've tried cross-domain AJAX techniques like Yahoo YQL and JsonP. While Yahoo YQL allows me to grab part of the source code, I'm facing ...

Sending image to the server with the help of JavaScript

Curious if there is a method to upload an image to the server using javascript or jQuery and then save the image path/name into a database. I am working on a Windows platform server in asp.net 1.1, revamping a web page that is 10 years old. Unfortunately, ...

What is the process by which a web browser executes a ".jsx" file while in development?

As a beginner in the world of react, I have successfully been able to execute the dev and build tests. One question that has been boggling my mind is how browsers handle ".js" files. I know that when a project is build, the browser runs the &quo ...

Using canvas elements to position divs in three.js

I am currently in the process of developing a custom animation player using Three.js for rendering objects, which is functioning perfectly. However, I am encountering difficulty when trying to incorporate control options at the bottom of the player (such a ...

Cross Domain Requests in Internet Explorer: Preflight not being sent

I have come across several similar discussions but none of the solutions provided have worked for me so far. Issue: In our current setup, we have three servers hosting our http-apis - two for testing and one for production. Lately, we have been deployin ...

Guide to switching content within a DIV when the up and down buttons are pressed using JavaScript and jQuery

I have a functional code with a timeline where each event is connected to the other. There are buttons to delete and copy data, but I want to implement functionality for swapping elements when the up or down button is clicked. I have provided a sample code ...