DanB
DanB

Reputation: 11

How do I Change JSON Object using Javascript

I have the following line in my code. It was generated by my IDE. Basically this line consists of a div which acts as an animated sidebar. The width of the sidebar is represented by the 'v' parameter (set here at 85).

<div id="sidebar" class="inner-element uib_w_5 uib_sidebar rightbar bar-bg thumb-bg bar-gutter" data-uib="layout/right_sidebar" data-ver="1" data-anim="{'style':'overlap', 'v':85, 'side':'right', 'dur':200}">

I would like to change the value of 'v' to 250 using a Script Tag.

I tried to insert the following script to overwrite the above data-anim attribute but it did not work.

<script>
 document.getElementById("sidebar").jsonObj['data-anim'] = "{'style':'overlap', 'v':250, 'side':'right', 'dur':200}"
</script>

Any ideas as to what's wrong with my <script> tag ?

Upvotes: 1

Views: 73

Answers (2)

DanB
DanB

Reputation: 11

I found the answer to my own question.

Here is the <script> that will work:

document.getElementById("sidebar").dataset.anim = "{'style':'overlap', 'v':250, 'side':'right', 'dur':200}";

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68373

use setAttribute of the sidebar element

it should be

var sidebar = document.getElementById("sidebar");
sidebar.setAttribute( "data-anim" , "{'style':'overlap', 'v':250, 'side':'right', 'dur':200}" );

read up this setAttribute documentation as well

document.getElementById("sidebar").setAttribute("data-anim", "{'style':'overlap', 'v':250, 'side':'right', 'dur':200}");

var abc = document.getElementById("sidebar").getAttribute("data-anim");

alert(abc);
<div id="sidebar" class="inner-element uib_w_5 uib_sidebar rightbar bar-bg thumb-bg bar-gutter" data-uib="layout/right_sidebar" data-ver="1" data-anim="{'style':'overlap', 'v':85, 'side':'right', 'dur':200}">

Upvotes: 1

Related Questions