最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get name of HtmlDivElement - Stack Overflow

programmeradmin2浏览0评论

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)

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)

Share Improve this question edited May 5, 2014 at 23:18 Pascal Goldbach asked May 5, 2014 at 7:50 Pascal GoldbachPascal Goldbach 1,0071 gold badge17 silver badges35 bronze badges 4
  • it's just element.name – kennypu Commented May 5, 2014 at 7:52
  • @Smashmaster - you mean element.className (without ()). It is a property, not a method. – PhistucK Commented May 5, 2014 at 7:52
  • stackoverflow./questions/5902161/… – CodeBird Commented May 5, 2014 at 7:53
  • 1 @kennypu: It would be, if div elements had a name attribute. But if you try that with a div, you'll get undefined. – T.J. Crowder Commented May 5, 2014 at 8:01
Add a ment  | 

3 Answers 3

Reset to default 9

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

You could use:

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

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

You need this function

var name = element.getAttribute("name");
发布评论

评论列表(0)

  1. 暂无评论