Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

184
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda