Poonam Bhatt
Poonam Bhatt

Reputation: 10342

How can I get name of element with jQuery?

How can I get name property of HTML element with jQuery?

Upvotes: 157

Views: 382838

Answers (7)

Doug Nintzel
Doug Nintzel

Reputation: 81

If anyone is also looking for how to get the name of the HTML tag, you can use "tagName": $(this)[0].tagName

Upvotes: 2

rjb
rjb

Reputation: 9116

Play around with this jsFiddle example:

HTML:

<p id="foo" name="bar">Hello, world!</p>

jQuery:

$(function() {
    var name = $('#foo').attr('name');

    alert(name);
    console.log(name);
});

This uses jQuery's .attr() method to get value for the first element in the matched set.

While not specifically jQuery, the result is shown as an alert prompt and written to the browser's console.

Upvotes: 8

Didier Ghys
Didier Ghys

Reputation: 30676

The method .attr() allows getting attribute value of the first element in a jQuery object:

$('#myelement').attr('name');

Upvotes: 2

user1106925
user1106925

Reputation:

To read a property of an object you use .propertyName or ["propertyName"] notation.

This is no different for elements.

var name = $('#item')[0].name;
var name = $('#item')[0]["name"];

If you specifically want to use jQuery methods, then you'd use the .prop() method.

var name = $('#item').prop('name');

Please note that attributes and properties are not necessarily the same.

Upvotes: 18

Dennis Traub
Dennis Traub

Reputation: 51694

var name = $('#myElement').attr('name');

Upvotes: 3

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76910

You should use attr('name') like this

 $('#yourid').attr('name')

you should use an id selector, if you use a class selector you encounter problems because a collection is returned

Upvotes: 265

Patricia
Patricia

Reputation: 7802

$('someSelectorForTheElement').attr('name');

Upvotes: 11

Related Questions