Can I access a hash stored in html elements data attribute with jquery?
html, javascript, jquery
Solution
If you store it as valid JSON, you can parse it, and get is content.
<p class='message' data-dependencies='{"#first":{"equal":"Yes"}}'>
Relevant Content
</p>
var json = $(".message").first().attr("data-dependencies");
// HTML5 browsers
// var json = document.querySelector(".message").dataset.dependencies;
var parsed = $.parseJSON(data);
alert(parsed["#first"].equal); // "Yes"
Or if you use jQuery's `.data()`, it will parse it automatically.
var parsed = $(".message").first().data("dependencies");
alert(parsed["#first"].equal); // "Yes"
Problem
I've got several html elements that I'm appending hashes to like so: ``` <p class='message' data-dependencies={'#first':{'equal':'Yes'}}> Relevant Content </p> ``` so that ``` $(".message").first().data("dependencies") ``` returns ``` {'#first':{'equal':'Yes'}} ``` But as a buddy just pointed out to me, this value is a string. So naturally the filter described below has a hard time with it. The goal of the filter is to be able to grab elements that have a specified key, in this case "#first". ``` $el.children().find("*").filter(function(){ var dependency_hash = $(this).data("dependencies"); if(dependency_hash != undefined && "#first" in dependency_hash){ return true } }); ``` Is there a way to access the hash as passed via the data object or is there another way I can structure the data so as to accomplish the same means of being able to select elements based on the key?