首页 > 解决方案 > Getting the value of the first object in dataset on a HTML DOM with javascript

问题描述

So I have a DOM like this:

<div data-info="{"partnerLink":"https://bing.com","fillColor":"rgba(10,91,144,1)"}"></div>

Is there any way to get the value of partnerLink (in this case https://bing.com) in JS?

I know it would be better to have data-partnerLink and data-fillColor but this is what I have for now.

标签: javascript

解决方案


Fix the object. The quotes you are using are wrong. Access the element using querySelector and get the attributes using getAttribute. Using dot notation print the object property

var a=document.querySelector('div')
var b=a.getAttribute('data-info');
console.log(JSON.parse(b).partnerLink)
<div data-info='{"partnerLink":"https://bing.com","fillColor":"rgba(10,91,144,1)"}'></div>


推荐阅读