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

javascript - custom attribute works only with element.getAttribute("attribute") but not "element.attr

programmeradmin1浏览0评论

I have just noticed, that if I give a custom attribute to an html element, for example:

<input type="button" id="my_button" custom_attr="custom_attr_text" value="value_text" />

then i can retrieve it like this:

document.getElementById("my_button").getAttribute("custom_attr");

and it will return "custom_attr_text", but if I do

document.getElementById("my_button").custom_attr;

then it returns undefined!

I also noticed that with a built in attribute (for example value or id) both of the above works fine! Could somebody please explain why is this happening?

I have just noticed, that if I give a custom attribute to an html element, for example:

<input type="button" id="my_button" custom_attr="custom_attr_text" value="value_text" />

then i can retrieve it like this:

document.getElementById("my_button").getAttribute("custom_attr");

and it will return "custom_attr_text", but if I do

document.getElementById("my_button").custom_attr;

then it returns undefined!

I also noticed that with a built in attribute (for example value or id) both of the above works fine! Could somebody please explain why is this happening?

Share Improve this question edited Dec 23, 2017 at 18:05 Isti115 asked Feb 21, 2013 at 19:50 Isti115Isti115 2,7483 gold badges36 silver badges38 bronze badges 2
  • It's a littlebit jQuery-specific, but see the duplicate of .prop() vs .attr(). If you want a only-plain-js explanation, see javascript.info/tutorial/attributes-and-custom-properties – Bergi Commented Feb 21, 2013 at 19:53
  • This also applies to existing attributes added to elements whose prototype doesn’t provide a property mapping to the attribute, e.g. <button src="xyz.jpg"></button>: button.src will be undefined. – Sebastian Simon Commented Jul 31, 2018 at 16:10
Add a comment  | 

1 Answer 1

Reset to default 19

Only certain standard attributes are directly mapped to properties. This is not the defined behavior for non-standard (custom) attributes.

The forward compatible way of using custom attributes is to prefix them with data-.

<input ... data-custom_attr="custom_attr_text" ... />

Then they become available in HTML5 compliant browsers as:

element.dataset.custom_attr

But in legacy browsers, you'll still need to use .getAttribute().

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论