18

I am working on an AngularJS project and the attributes are numerous in many of my HTML elements:

  <button type="submit" 
          ng-click="Page.UI.DetailView.ExecuteFunction()" 
          ng-disabled="step5.$invalid" 
          class="btn btn-success pull-right">
      Submit this Product
  </button>

Is there a standardized convention for the order of these attributes? Alphabetical? Grouped by meaning (e.g. all angular attributes together)? Standard HTML attributes ("type" for example) first?

7
  • 7
    No, there's no standard. W3C says that the order of attributes does not matter. Find some Angular code examples somewhere on the Internet or in an Angular book, and follow whatever convention they've set there; chances are it's close to "correct," if not actually "correct." Commented Dec 17, 2015 at 16:48
  • 1
    I dont think so. But if you look at the dom in console it is alphabetically ordered.
    – Abel D
    Commented Dec 17, 2015 at 16:49
  • 1
    In addition, you can find loads of advice by Googling "Ordering attributes in HTML tags." Commented Dec 17, 2015 at 16:52
  • Thanks AbelD and @RobertHarvey. I am indeed finding plenty of opinions via Google, but was hoping that there is a more standard approach. Thanks again. Commented Dec 17, 2015 at 16:58
  • 1
    @AbelD Alphabetical ordering of HTML attributes sounds like the worst idea ever though, for a developer.
    – Alternatex
    Commented Dec 18, 2015 at 13:15

2 Answers 2

14

There is no standard. Optimize for ease of understanding, and try to be consistent.

Personally I think it's also good to always put the id attribute first, so that it's easier for testers to find it.

1
  • 3
    I find the most important thing is to be concise. If working in a team, make sure you follow the same pattern for the aforementioned reason. I tend to stick to type, id/for, name, class. If I'm using angular then all ng--attributes will go first. It's down to personal preference.
    – mausworks
    Commented Dec 17, 2015 at 17:08
0

Use class >> id >> style, in this order.

I am developing a framework, and it generates html code as one of it's functionalities.

For example you can create a div using html($attributes)

  • You can use the $attributes as a string like id="one" class="two" or simply two (to be converted into class="two");
  • You can use the $attributes as an array like ['data-target' => 'test', 'style' => 'margin: 0;'] or simply ['class1 class2', 'myId', 'padding: 1em;'] to be converted to ['class' => 'class1 class2', 'id' => 'myId', 'style' => 'padding: 1em;'].

Why?

Because class, id and style are the most used attributes in tags, in this order, and they are universal. You can use them in every tag inside html's <body>, not like href, name, readonly and other attributes that are used in only a short range of html tags.

Not the answer you're looking for? Browse other questions tagged or ask your own question.