Is using the class attribute only for javascript purposes generally accepted or should it be restricted to CSS?
Is using the class attribute only for javascript purposes generally accepted or should it be restricted to CSS? I know it probably doesn't matter; but I'm using the class attribute to find elements with JavaScript, but there is no equivalent CSS class. Visual studio warns me of this, leading to think it's not a good practice. Is this generally accepted as OK or frowned upon?开发者_如何学C I realize this a bit subjective, but I think the question is valid.
Visual Studio is being needlessly pedantic. It's common practice to add classes for access by JavaScript.
Throughout our company's code, we use CSS classes to help with element selection all the time. I wouldn't worry about the Visual Studio warnings; a lot of that stuff was designed before the jQuery behemoth reared its head.
It is perfectly ok if you're using jQuery but if you are using plain JavaScript then use id since you can get the element by calling getElementById() and there is no simple equivalent for class.
I can't speak for the general community, but I've thought about this a lot and my own feelings are that it is acceptable if the elements represent some logical class, some things that could reasonably be styled the same way, even if they aren't currently. Just tagging a bunch of otherwise unrelated things with the same class so you can grab them with one call feels like cheating to me.
精彩评论