'Custom Attributes values Javascript

The innline style Attributes has values such as style = "color: green; background: red;". If I want to dynamically change only the background I change with the javascript Attribute style, I do it with: element.style.background = "blue".

How to create a "custum Attributes" so that the values within an attribute change dynamically.

For example: myAttributes = "car: mercedes; truck: volvo;" so that I change only car values dynamically as style changes, as an element.myAttributes.car = "ferrari" or with setAttributes ("myAttributes", car = "ferrari" ). Is there a possibility to do this, or some similar alternative, some idea?

var get_att = document.getElementById("demo").getAttribute("vehicles");

// how to get vehicles attributes and convert to object?

const vehicles = {car:"mercedes", truck:"volvo"}; 
// const vehicles = get_att; 
// how to add the get_att variable here?

vehicles.car = "ferrari";

const setVehicles = (Object.entries(vehicles).map(([k, v]) => `${k}: ${v}`).join("; "));
console.log(setVehicles);

document.getElementById("demo").setAttribute("vehicles", setVehicles);
<div id="demo" vehicles="car: mercedes; truck: volvo"></div>


Solution 1:[1]

HTML Attributes must be a string value you can't parse this like a object. For parse attributes you can you JSON.stringify() and JSON.parse() for setting you attribute values.

Example: setting:

const el = document.body 
el.setAttribute("my-attribute", JSON.stringify({car: "bmw", owner: "user1234"}))

and parse

    JSON.parse(document.body.getAttribute('my-attribute'))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 vitaliyirtlach