Usually when I need some Id of a random object (stored on the server) in JavaScript I’m using the following approach:
<div id="chat-wrap-29" class="chat-wrap">...</div>
<div id="chat-wrap-28" class="chat-wrap">...</div>
This is how I know that I can retrieve the chat wrap ID in a JS script and send it via AJAX on the server.
In order to get the id I have to retrieve the id attribute (this.getAttribute("id")), and do some string manipulation in the script.
An cleaner way would be to use something like this:
<div class="chat-wrap" chatId = "29">...</div>
<div class="chat-wrap" chatId = "29">...</div>
This way there would be less IDs declared in the DOM and I would avoid that string manipulation. Has this solution any drawbacks? What would be the best practice in the situation I’ve described?
Thank you!
If you are going to store data in attributes, you should use HTML5
data-*attributes – that’s their purpose, as described in the spec.Some JavaScript libraries, such as jQuery have native support for them.