Is it always bad practice to start an ID with a number? (CSS)

后端 未结 5 2018
暗喜
暗喜 2020-12-20 15:54

In my project I have submissions and comments, each with an ID. Currently the ID\'s are just numeric and correspond to their database ID\'s. Everything is working fine but w

相关标签:
5条回答
  • 2020-12-20 16:29

    I suggest you to use prefixes "comment-ID" or "post-ID".

    If you need the id in JavaScript, you just have to id.substring(8) (for "comment-")

    0 讨论(0)
  • 2020-12-20 16:33

    Yes, using numbers as HTML element IDs is bad practice.

    1. It violates W3C specification.
      You noted this in your question, and it is true for every HTML specification except HTML5

    2. It is detrimental to SEO.
      Search-engine optimized HTML element IDs SHOULD reflect the content of the identified element. Check out How To Compose HTML ID and Class Names like a Rockstar by Meitar Moscovitz. It provides a good overview of this concept.

    3. There can be server-side scripting issues.
      Back when I first started programming in ASP classic, I had to access submitted form fields by a syntax like Request.Form("some_id"). However, if I did Request.Form(1) it would return the value of the second field in the form collection, instead of the element with an Id equal to 1. This is a pretty standard behavior for working with collections. Its also similar with javascript, and could make your client side scripting more complicated to maintain as well.

    0 讨论(0)
  • 2020-12-20 16:33

    The HTML 5 Specification lifts this restriction. If you're worried about validity you might simply consider changing the DTD to HTML5's.

    http://www.w3.org/TR/html5/elements.html#the-id-attribute

    0 讨论(0)
  • 2020-12-20 16:42

    If you're manipulating the element then you can just use $(this).jQueryOperation() - therefore you can have a prefix without having to replace anything!

    0 讨论(0)
  • 2020-12-20 16:45

    The best way for your need is having the prefix for your class, I mean something like item-x and x is the number that you need.

    But from my personal experience, it is better to use classes for your elements, and you know that you must use classes if the item is not unique in the page

    0 讨论(0)
提交回复
热议问题