Can I access the hash stored in the data attribute of html elements using jquery?

I have several html elements that I add to the hashes like this:

<p class='message' data-dependencies={'#first':{'equal':'Yes'}}> Relevant Content </p> 

so that

 $(".message").first().data("dependencies") 

returns

 {'#first':{'equal':'Yes'}} 

But as soon as a friend pointed me, this value is a string. Therefore, of course, the filter described below is difficult to cope with.

The purpose of the filter is to capture elements that have the 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 passed through the data object, or is there another way that I can structure the data to execute the same tool that allows me to select items based on the key?

+4
source share
3 answers

If you store it as valid JSON, you can parse it and get the 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 .data() , it will parse it automatically.

 var parsed = $(".message").first().data("dependencies"); alert(parsed["#first"].equal); // "Yes" 
+5
source

Use JSON.parse. There are policies 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 } }); 
+2
source

You probably want to serialize your data as JSON http://json.org/ and then return it to JS. You can use jquery parser http://api.jquery.com/jQuery.parseJSON/

0
source

Source: https://habr.com/ru/post/1443098/


All Articles