How can I get data-value
country using jQuery? I need this in variable:
var country = ...;
HTML:
<a id="obj-details" data-value="{city:'berlin', street: 'mozart', postal_code: '55555', country: 'DE'}">test</a>
Answer: Use the CSS Attribute Selector You can use the CSS attribute selectors to find an HTML element based on its data-attribute value using jQuery. The attribute selectors provide a very powerful way to select elements.
Use the querySelector method to get an element by data attribute, e.g. document. querySelector('[data-id="box1"]') . The querySelector method returns the first element that matches the provided selector or null if no element matches the selector in the document.
To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase). Each property is a string and can be read and written.
ready(function() { $('#list li'). click(function() { alert($(this). attr("id")); alert($(this). text()); }); });
To read data-value
attribute use below jQuery :
$("#obj-details").data('value');
and to read country
from the data-value
use below jQuery :
var value = $("#obj-details").data('value');
var obj = eval('(' +value + ')');
var country = obj.country;
alert(country );
Demo
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