Open In App

How to get the object’s name using jQuery ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to find the name of an element using jQuery. The name attribute can be applied to multiple elements in HTML and is used to specify a name for any element. The name attribute of any element can be found out using the attr() method. This method is used to find the value of any attribute of the first element in the matched set. 

As we need to find the name of an element, we will use this method on the required element and pass “name” as the parameter in this method.

Syntax:

// Select the required element
let selectedElem = $("elemToSelect");

// Get the name of the element
// using the attr() method
let elementName = selectedElem.attr('name');

console.log("The name of this element is:",
            elementName);

The example below illustrates the above approach:

Example: In this example, we will create a clone of the object using this method.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <script src=
    </script>
</head>
 
<body>
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
 
    <b>
        How to get the object's name
        using jQuery?
    </b>
     
    <form>
        <label for="name">Name:</label>
        <input type="text" id="name" name="fname" />
        <br><br>
         
        <label for="age">Age:</label>
        <input type="number" id="age" name="age" />
        <br><br>
         
        <label for="address">Address:</label>
        <textarea id="address" name="address"></textarea>
    </form>
 
    <script>
     
        // Select the required element
        let selectedElem = $("#name");
 
        // Get the name of the element
        // using the attr() method
        console.log("The name of this element is:",
            selectedElem.attr('name'));
 
        let selectedElem2 = $("#age");
        console.log("The name of this element is:",
            selectedElem2.attr('name'));
 
        let selectedElem3 = $("#address");
        console.log("The name of this element is:",
            selectedElem3.attr('name'));
    </script>
</body>
 
</html>


Output:



Last Updated : 30 May, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads