lastnoob
lastnoob

Reputation: 648

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.

Upvotes: 0

Views: 231

Answers (2)

ellipsis
ellipsis

Reputation: 12152

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>

Upvotes: 2

Jack Bashford
Jack Bashford

Reputation: 44087

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>

Upvotes: 1

Related Questions