Reputation: 15
For starts I have this HTML with example data within it:
<div class="card {toggle:'someinformation'}">
<div class="off"></div>
<div class="on {toggle:'getThisInfo'}"></div>
</div>
I want to use jQuery and retrieve this information. Upon asking someone they told me to use the follow (which did not work):
var $card = $(this);
var this_card = $card.children(".on").metadata()["toggle"];
and was told the value of "this_card" would be 'getThisInfo' -- which it did not work. And yes, I did make sure metadata was included in HTML and jQuery as well.
Any other suggestions?
Upvotes: 0
Views: 98
Reputation: 15558
Just use the HTML5 data-*
attribute:
<div class="card" data-toggle="someinformation">
<div class="off"></div>
<div class="on" data-toggle="getThisInfo"></div>
</div>
Then access it using jQuery's .data()
function, like this:
var $card = $(this),
this_card = $card.children(".on").data("toggle"); // "getThisInfo"
Update:
Based on the extra code posted this should work perfectly for you:
var $on_cards = $(".card > .on:visible");
if ($on_cards.length == 2) {
var $card = $('.card:first'), // was $(this), replaced just for this demo
this_card = $card.children(".on").data("toggle"),
$matched_cards = $on_cards.filter('[data-toggle="' + this_card + '"]'),
event_name = "no_match";
if ($matched_cards.length === 2) {
event_name = "found_match";
}
}
This uses jQuery's Attribute Equals Selector to find .on
elements with the same data-toggle
value.
Important: if you need to change the .on
's value then don't use jQuery's .data()
function to do so, use:
$(selector).attr('data-toggle','your-new-value');
This is because .attr()
and .prop()
update the attributes in the HTML (which the [data-toggle=""]
selector checks) whereas .data()
updates an internal jQuery object without affecting the actual element.
Here it is working: http://jsfiddle.net/c4fQ3/1/ (try changing the .on
element's data-toggle
value)
Upvotes: 3