0

Here's how I change the value of an existing attribute:

element.attributeName = "value"


But is it OK to use the above method to create a new attribute?

Notes:

  1. JavaScript only.
  2. Please provide the relevant documentation.
  3. I don't need to support old browsers.
  • Possible duplicate of http://stackoverflow.com/questions/7677930/using-createattribute-vs-just-setting-the-attribute-directly – Razvan Feb 14 '14 at 13:53
  • I'm already aware of `Element.setAttribute`. Please read my question again. –  Feb 14 '14 at 13:57
  • There's nothing wrong with `setAttribute`. I just wonder if the above method is OK or not. –  Feb 14 '14 at 14:00
  • 2
    This question is perfectly valid. It's not a matter of preference or opinion, the question raises a question whether it's valid code. – Ronni Egeriis Persson Feb 14 '14 at 14:10

2 Answers2

2

element.attribute = x works for W3C defined attributes or already specified node attributes on your element.

This is the exact working as it reads on MDN:

if attributeName is a W3C defined attribute and an attribute node for the element (e.g., id),
that Attribute Node gets assigned the value of x

if attributeName isn't a W3C defined attribute or an attribute node for the element, 
the element's (JavaScript object) attributeName property is assigned the value of x

See Syntax section on this page: https://developer.mozilla.org/en-US/docs/Web/API/Node.attributes

Examples

Take below DOM element

<div data-goals="3" id="container"></div>

You would be fine modifying data-goals through

document.getElementById('container').dataGoals = '4';

You are also able to add new attributes, if these are defined by W3C, e.g. title

document.getElementById('container').title = 'This is a title';

But you should not expect to be able to set a new attribute which is not defined by W3C

document.getElementById('container').myOwnAttribute = 'something';
Ronni Egeriis Persson
  • 2,209
  • 1
  • 21
  • 43
  • 2
    Something important to note: some attributes have different DOM names than attribute names, for example `class` is `className` or `value` is `defaultValue`. – Mori Feb 15 '14 at 08:28
-2

Here is your answer: add new attribute

EDITED:

pure JavaScript:

1st 2nd

Community
  • 1
  • 1
melvas
  • 2,346
  • 25
  • 29