Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I access a hash stored in html elements data attribute with jquery?

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?

like image 582
biagidp Avatar asked Feb 19 '23 15:02

biagidp


2 Answers

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"
like image 141
I Hate Lazy Avatar answered Feb 21 '23 04:02

I Hate Lazy


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
    }
});
like image 31
Will Shaver Avatar answered Feb 21 '23 04:02

Will Shaver