Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

192
Views
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 video" + ar.next-_video);

but setting it is proving difficult, for example:

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

instead of

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

you should do like this

var ar = JSON.parse(videoElement.getAttribute("data-info"))
ar.next_video = "1";
videoElement.setAttribute("data-info", JSON.stringify(ar));
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!