What is the method for extracting the name and id of a tag when the mouse hovers over it?

Looking for a way to display the name and id of a tag when it is in focus.
For instance,
if focus is on an input with id 1th, display input and 1th using console.log.
if focus is on a textarea with id 2th, show textarea and 2th through console.log.

let ob = window.document.getElementsByTag("");
function getNameAndId(event){
    console.log(tag's name and id);
}
ob.addEventListener("focus",getNameAndId); 

 
content:<input id="1th" type="text">
<br/>
content:<textarea id="2th" cols=6 rows=5></textarea>
<br/>
content:<input id="3th" type="text">
<br/>
content:<input id="4th" type="text">
 

In my example, I am unsure how to define ob.

let ob = window.document.getElementsByTag("");

Is there a way to display the tag's name and id when it is focused?

console.log(tag's name and id);

Answer №1

If you want to achieve event delegation, simply assign the event listener to a parent element (such as the body) and use capture by passing in true as the third parameter of the addEventListener method. Then, access the specific element using event.target:

function getNameAndId(event) {
    var target = event.target;
    console.log("Tag: " + target.tagName);
    console.log("Id: " + target.id);
}
document.body.addEventListener("focus", getNameAndId, true);
 
content:<input id="1th" type="text">
<br/>
content:<textarea id="2th" cols=6 rows=5></textarea>
<br/>
content:<input id="3th" type="text">
<br/>
content:<input id="4th" type="text">

Please note: By implementing this technique, the focus event will be captured for all focusable elements within the body. You can further refine this by selecting a different parent element or filtering based on the tagName of the element.

Answer №2

Start by identifying the active element's ID.

let activeElementId = document.activeElement.id;

Next, retrieve the tag name using the following code snippet.

let tagName = document.getElementById(activeElementId).tagName;

Finally,

console.log("Tag Name: " + tagName + ", Active Element ID: " + activeElementId);

Answer №3

If you're looking to enhance the scalability, consider enclosing this in a more versatile wrapper.

<html>
<head>
    <script>
            window.addEventListener("focusin", (event)=> {
                if (event && event.target) {
                    console.log(`ID = ${event.target.getAttribute("id")}`);
                    console.log(`NAME = ${event.target.tagName}`);
                }
            });
    </script>
</head>
<body>
    <input id="hello" style="border: 1px solid #000; padding: 20px;">
</body>

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

Display different data in an HTML table for each individual click on the "Read more" event

I am currently extracting data from a SQL table to exhibit it in an HTML table. The issue I am facing is that I would like to implement a "Read More" feature to prevent clutter in the table. As I am retrieving the data row by row, I am utilizing a class n ...

The attempt to convert the value "NaN" to a number (data type number) at the specified path "markupPercentage" was unsuccessful

When I try to use Excel to update products, I encounter an error related to the presence of NaN. Here is the specific error message: CastError: Cast to Number failed for value "NaN" (type number) at path "markupPercentage" messageFormat: undefine ...

Fetch a single random profile image from a Facebook user's list of friends using Javascript

I'm currently facing an issue with displaying a random profile picture of the user's friends on Facebook. I attempted to troubleshoot it myself but ended up crashing the login button and now it's not functioning properly. Can someone please ...

"Flashes of canvas in constant motion between animated scenes

I have a practical exercise to do for school, but I am very new to HTML/JS. The issue I am facing is that my canvas is flashing, like it erases one image and then quickly displays another. I want both images to be displayed at the same time. Here is the co ...

Is it possible to execute a command in the terminal that is related to the package.json file?

Objective Create a program to analyze user engagement data for a hypothetical menu planning calendar app. The program should be able to track the activity of users based on their meal planning within the app. Data Overview In the ./data folder, there ...

Is there a way to avoid using Webpack and React for packaging?

Is there a way for me to debug JS and tweak CSS without webpack packing everything together in 'development mode'? Can I configure webpack to keep my sources separate? Here's the content of my webpack.config.js: const path = require(&apos ...

Angular JS displays an error message when the user selects an input field and fails to provide any input

On my wizard steps application, I have implemented Angular JS validation that displays errors when the user enters and removes a character in the input field. However, I am trying to figure out how to show the error message if the user tabs onto the fiel ...

The data from req.body is mysteriously missing from Postman

When sending the post request, I used raw and json format... Here is the header configuration This is the code: //app.js const port = process.env.PORT || 3000; const express = require ('express'); const app = express(); const jsonParser = re ...

Using jQuery, retrieve the "select" element within a specific row of a

I am working on a table row that has the following HTML structure: When the user interacts with the "Name" field, I trigger the "select" event and pass it to the nameDropChanged function. Once I have a reference to this select element, I need to change th ...

Is it possible to utilize filter in place of forEach in Javascript?

Is there a way to refactor the function below that currently uses forEach to instead use filter? I've searched online but couldn't find a suitable solution. pendingPaymentsUtils.getPendingPayment = paymentId => { const payments = pendingPay ...

Eradicate white space in a JavaScript code

Calling all JS programmers! Here's a challenge for you, check out this demo: https://codepen.io/gschier/pen/jkivt I'm looking to tweak 'The pen is simple.' to be 'The pen issimple.' by removing the extra space after 'is& ...

Oops! It seems like there is an issue with reading the property 'filter' of an undefined object. Any ideas on how to resolve this error

Having an issue with a custom filter that is causing an error "ERROR TypeError: Cannot read property 'filter' of undefined". I need help fixing this as it's preventing anything from rendering on the page. Any suggestions on what changes I sh ...

Invoke a TypeScript function from the HTML code embedded within a TypeScript component

In my pop-up window, there are 2 buttons: Update and Delete. I need to implement functionality so that when the Update button is clicked, the current pop-up should disappear and a new editable pop-up with the same fields should appear, along with two addit ...

Instructions for adding a unique custom external CSS link, such as Bootstrap CSS, to a specific REACT component

Is it possible to incorporate custom CSS from the Bootstrap website into a React component? Since this CSS file cannot be imported directly, what steps should I take to include it? <link href="https://getbootstrap.com/docs/4.5/dist/css/bootstrap. ...

Is it possible to invoke the same function twice on HTML5 Canvas?

I'm feeling overwhelmed as a beginner with HTML 5 canvas. I'm struggling with this particular function: function drawcircle(x,y) { context.save(); context.strokeStyle = '#00ff00'; context.fillStyle = '#000000'; ...

Utilize socket.io to send information from a nodejs server to an html webpage

I've been working on transferring data from Node.js to HTML using socket.io. Initially, I successfully transferred text from Node.js to HTML with the following code: Node.js code : app.post('/timer', function(req, res){ ...

Angularjs - How come I am able to modify an object but not the list (ng-repeat) from a separate view?

After updating the customers object in the console, I noticed that the list (ng-repeat) is not reflecting the changes. What should I do? Interestingly, it works fine when I implement this function and view2.htm's HTML inside page.htm. HTML "page.htm" ...

javascript - What is the method to determine if an array contains a negative number?

As a novice JavaScript programmer, I found myself in need of checking whether an array of integers contained any negative values, but didn't want to resort to looping through each element and returning multiple times. After considering various options ...

Initiating a GET request to retrieve the file generated by the server

I am currently delving into the Mean stack and have encountered a challenge with downloading a file from my server-side application using the Angular front end. Despite successfully generating the file on the back end, clicking the download button on the f ...

Managing multiple carousels simultaneously using the middle mouse button in Swiper.js

I am currently utilizing 5 carousels on my screen, all of which are operated by the same navigation buttons. In addition to this, I require the ability to control them using the middle mouse scroll. However, when I activate the mouse wheel control, only ...