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?
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"
Use JSON.parse. There are polyfills if you need support in older browsers.
$el.children().find("*").filter(function(){
var dependency_hash = $(this).data("dependencies");
var parsed_hash = JSON.parse(dependency_hash);
if(parsed_hash != undefined && "#first" in parsed_hash ){
return true
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With