Pascal Goldbach
Pascal Goldbach

Reputation: 1007

Get name of HtmlDivElement

I want to get the name of an HtmlDivElement object.

<div class=a name=b>... </div>

I know it is possible to get the class name by using the method object.className(), but is there a equivalent for the name (I want to get 'b') ?

(sorry about my english, I'm French)

Upvotes: 2

Views: 10918

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074585

I know it is possible to get the class name by using the method object.className()...

No, it's a property: object.className

...but is there a equivalent for the name (I want to get 'b') ?

For elements where name is a valid attribute, it would be object.name. But div elements don't have a name attribute. The only valid attributes for div elements are the standard global ones, which don't include name.

You can, of course, put any attribute on an element if you really want to, it just makes your HTML invalid. You can retrieve those attributes with getAttribute:

console.log(object.getAttribute("name"));

Live Example

Upvotes: 9

KhorneHoly
KhorneHoly

Reputation: 4766

You need this function

var name = element.getAttribute("name");

Upvotes: 2

xdazz
xdazz

Reputation: 160863

You could use:

var name = element.getAttribute('name');

And note it's element.className not element.className(), element.className is not a function.

Upvotes: 2

Related Questions