Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you set an attribute value that is a JSON literal within a DOM

I am trying to set the value of a key value in a JSON literal that is contained with a tag, for example, in the snippet below the data-info is the JSON literal.

<video
  id="myPlayer_1"
  width="90%"
  poster="videos/posters/NoVideoPoster.png"
  data-info="{"start_time": "71522", "end_time":"71622", next_video:"0"}">
</video>

Now I can read the attribute using the following code:

var ar = JSON.parse(videoElement.getAttribute("data-info"))
console.log("next route" + ar.next-_video);

but setting it is proving difficult, for example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

videoElement.setAttribute("data-info.next_video", "1");

produces:

<video
  id="myPlayer_1"
  width="90%"
  poster="videos/posters/NoVideoPoster.png"
  data-info="{"start_time": "71522", "end_time":"71622",next_video: "0"}"
  data-info.next_video = "1">
</video>

Which is obviously not correct. Can anyone help?

>Solution :

You have to set the whole attribute. To the DOM, remember, it’s just a string.

So for instance, after having read and parsed it:

var ar = JSON.parse(videoElement.getAttribute("data-info"))

you can update it and set it again by converting back to JSON (a string):

ar["next-video"] = 1;
videoElement.setAttribute("data-info", JSON.stringify(ar));

If you’re in control of the element and you need to update just parts of that information, you might consider separate data-* attributes rather than a single one with JSON in it. For instance:

<video
    id="myPlayer_1"
    width="90%"
    poster="videos/posters/NoVideoPoster.png"
    data-start-time=71522
    data-end-time=71622
    data-next-video=0
></video>

Then updating the "next video" is:

videoElement.dataset.nextVideo = "1";

Note how dataset converts data-next-video to nextVideo. See the details on MDN.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading