简体   繁体   中英

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.

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> 

First, you need to fix your quotes like so:

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

(All I changed were the very first and last "" into '' so it wouldn't interfere with the inner quotes).

And you can do it like this:

 var div = document.querySelector("div"); //Add an ID and use getElementById if there's more than one div var partnerLink = JSON.parse(div.getAttribute("data-info")).partnerLink; console.log(partnerLink); 
 <div data-info='{"partnerLink":"https://bing.com","fillColor":"rgba(10,91,144,1)"}'></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM