Reputation: 1242
I have an unordered list, where I am using an ID to identify the current list item that was last clicked. On click of a different item, I am using js to switch the id to a different item in the list, so that styling could be applied.
It seems intuitive to me that a unique item that can only be used once (a selected li item) should be identified as an ID, and that is why I did that, but I was told it is bad practice to do so.
Upvotes: 3
Views: 516
Reputation: 1129
Your question actually has a couple of interesting components, let me try to answer them as good as I can :-)
You could say it's a justifiable case, if the element really is unique, then there's no real harm in "moving" the ID with JavaScript.
BUT
In your description you touch on something more fundamental:
If this is the case (you change the ID for styling), then I'd recommend using a class instead. People previously already gave you a good hint, something like an "is-active" class would be very useful as it's less specfic than an ID, can be used on multiple items if needed and if you use classes that determine a state (like "is-active", "has-children", "is-animating", etc.), it's really easy to re-use them in later parts of code as well and it is clear what the element is doing at the moment.
A little code for reference:
HTML
<ul>
<li>Some item</li>
<li class="is-active">Some item</li>
<li>Some item</li>
<li>Some item</li>
</ul>
CSS
.is-active {
color: #eee;
background-color: #222;
}
jQuery
// You probably want a bit more specific selector, but it's just an example.
$('li').on('click', function() {
var $element = $(this),
$elements = $('li');
if (!$element.hasClass('is-active')) {
$elements.removeClass('is-active');
$element.addClass('is-active');
}
});
Upvotes: 3
Reputation: 10698
I wouldn't do so. This rather seems an opportunity for you to discover HTML 5's data attribute, which you can use for both CSS styling (using attribute selector) and JS use (with dataset
or jQuery's .data()
method).
Quick definition from MDN :
HTML5 is designed with extensibility in mind for data that should be associated with a particular element but need not have any defined meaning. data-* attributes allow us to store extra information on standard, semantic HTML elements without other hacks such as classList, non-standard attributes, extra properties on DOM, or setUserData.
In HTML side :
<!-- You can use data without value, and just test its presence -->
<li data-selected>
...
</li>
In CSS :
li[data-selected]{
...
}
Upvotes: 3
Reputation: 89
Since you might need to reference the specific id of an element at some future point, changing it is probably a bad idea. In your case it would be better to just apply a class to the last item clicked.
Upvotes: 0