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:
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?
CodePudding user response:
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.
CodePudding user response:
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));