I run a music blog using WordPress and I have a custom music player for it. Every time a post has a song attached to it, I want to create a way to hold that information and later access custom variables. What I need is something along the lines of…
<div class="playable"
title="Song Title"
mp3="URL"
soundcloudLink="https://soundcloud.com/cashcash/take-me-home-jordy-dazz">
</div>
Then in my $(document).ready()
function I would need a function that finds all objects of class “playable” and be able to access the title tag, mp3 tag, soundcloudLink tag, etc.
Any easy suggestions?
It sounds like you’re looking for
data-*
attributes:E.g., they always pass validation, and they’re only for your use.
So for instance:
When you need to access that information, you get a jQuery object for the
div
, and then useattr("data-mp3")
ordata("mp3")
to access it. (Or without jQuery, get theHTMLDivElement
and usegetAttribute
.) Note that I haven’t changedtitle
.title
is a valid attribute, and accessible via.prop("title")
on jQuery instances or via.title
on DOM elements.Note that
data
is assymetrical: It reads fromdata-*
attributes for initialization, but doesn’t write to them.You can try the data- attribute which can easily be retrieved by .data() method.
HTML:
JQuery
You can use the
.hasClass()
jquery function to display the attributes of the elements with that class. Add an ID to the element like in this case I added test.. here is how to alert them.This one displays the soundcloud link and the title if the element has the class playable. here is a fiddle. http://jsfiddle.net/uprosoft/2Frk3/3/