Home > Enterprise >  Custom Attributes values Javascript
Custom Attributes values Javascript

Time:03-07

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?

CodePudding user response:

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'))

CodePudding user response:

Taken from another question - Custom attributes - Yea or nay?

HTML 5 explicitly allows custom attributes that begin with data. So, for example, Hello

is valid. Since it's officially supported by a standard, I think this is the best option for custom attributes. And it doesn't require you to overload other attributes with hacks, so your HTML can stay semantic.

  • Related