javascript - What is the best way to access an element through a data-attribute whose value is an object (JSON)? -
say have following element:
<div class='selector' data-object='{"primary_key":123, "foreign_key":456}'></div>
if run following, can see object in console.
console.log($('.selector').data('object'));
i can access data other object.
console.log($('selector').data('object').primary_key); //returns 123
is there way select element based on data in attribute? following not work.
$('.selector[data-object.foreign_key=456]');
i can loop on instances of selector
var foreign_key = 456; $('.selector').each(function () { if ($(this).data('object').foreign_key == foreign_key) { // } });
but seems inefficient. there better way this? loop slower using selector?
you can try the contains selector:
var key_var = 456; $(".selector[data-object*='foreign_key:" + key_var + "']");
i think may gain little speed here on loop in example because in example jquery json parsing value of attribute. in case it's using js native string.indexof()
. potential downside here formatting important. if end space character between colon , key value, *=
break.
another potential downside above match following:
<div class='selector' data-object="{primary_key:123, foreign_key:4562}"></div>
the key different still match pattern. can include closing bracket }
in matching string:
$(".selector[data-object*='foreign_key:" + key_var + "}']");
but again, formatting becomes key issue. hybrid approach taken:
var results = $(".selector[data-object*='" + foreign_key + "']").filter(function () { return ($(this).data('object').foreign_key == foreign_key) });
this narrow result elements have number sequence make sure exact value filter.
Comments
Post a Comment